scala – 如何确定类型参数是否是特征的子类型?
发布时间:2020-12-16 09:22:02 所属栏目:安全 来源:网络整理
导读:假设我有以下类型 class Footrait Bar 有没有办法建立一个接受Type参数T的方法,并确定T是否为Bar?例如, def isBar[T : Foo: Manifest] = classOf[Bar].isAssignableFrom(manifest[T].erasure) 可悲的是,isBar [Foo with Bar]是假的,因为擦除似乎消除了mixin
假设我有以下类型
class Foo trait Bar 有没有办法建立一个接受Type参数T的方法,并确定T是否为Bar?例如, def isBar[T <: Foo: Manifest] = classOf[Bar].isAssignableFrom(manifest[T].erasure) 可悲的是,isBar [Foo with Bar]是假的,因为擦除似乎消除了mixins. 另外,显示[Foo with Bar]<:<清单[Bar]是假的 这是可能的吗 我看了这个问题:How to tell if a Scala reified type extends a certain parent class? 但是这个答案并不适用于混合特征,因为它们似乎被清除,如上所述. 解决方法
这可以用
TypeTags(至少2.10M7)来实现:
scala> class Foo; trait Bar defined class Foo defined trait Bar scala> import reflect.runtime.universe._ import reflect.runtime.universe._ scala> def isBar[A <: Foo : TypeTag] = typeOf[A].baseClasses.contains(typeOf[Bar].typeSymbol) isBar: [A <: Foo](implicit evidence$1: reflect.runtime.universe.TypeTag[A])Boolean scala> isBar[Foo] res43: Boolean = false scala> isBar[Foo with Bar] res44: Boolean = true TypeTags提供Scala类型的1:1翻译,因为它们代表编译器知道的类型.因此,他们比普通的老清单更强大: scala> val fooBar = typeTag[Foo with Bar] fooBar: reflect.runtime.universe.TypeTag[Foo with Bar] = TypeTag[Foo with Bar] 使用方法tpe,我们可以完全访问Scalas新的反射: scala> val tpe = fooBar.tpe // equivalent to typeOf[Foo with Bar] tpe: reflect.runtime.universe.Type = Foo with Bar scala> val tpe.<tab><tab> // lot of nice methods here =:= asInstanceOf asSeenFrom baseClasses baseType contains declaration declarations erasure exists find foreach isInstanceOf kind map member members narrow normalize substituteSymbols substituteTypes takesTypeArgs termSymbol toString typeConstructor typeSymbol widen (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |