如果我有一个方法...如何使用新的反射API来判断数组的组件类型是否符合类型参数?
def arrayConformsTo[A](as: Array[_]) = ???
...这里需要我可以添加语境下界限到A
。我希望此方法查看Array
的组件类型,如果这是A
的子类型,则返回true。因此,举例来说:
arrayConformsTo[Int](Array(1, 2, 3)) //returns true
arrayConformsTo[String](Array(1, 2, 3)) //returns false
此前2.10,这一切都已经完成如下:
def arrayConformsTo[A: Manifest](as: Array[_]) =
ClassManifest.fromClass(as.getClass.getComponentType) <:< manifest[A]
但是这个现在废弃警告
<console>:8: warning: method <:< in trait ClassManifestDeprecatedApis is deprecated: Use scala.reflect.runtime.universe.TypeTag for subtype checking instead
ClassManifest.fromClass(as.getClass.getComponentType) <:< manifest[A]
^
<console>:8: warning: value ClassManifest in object Predef is deprecated: Use scala.reflect.ClassTag instead
ClassManifest.fromClass(as.getClass.getComponentType) <:< manifest[A]
我的第一个猜测这个编译如下:
scala> def arrayConformsTo[A: reflect.ClassTag](as: Array[_]) =
| reflect.ClassTag(as.getClass.getComponentType) <:< implicitly[reflect.ClassTag[A]]
但是,这给出了一个弃用警告以及
<console>:8: warning: method <:< in trait ClassManifestDeprecatedApis is deprecated: Use scala.reflect.runtime.universe.TypeTag for subtype checking instead
reflect.ClassTag(as.getClass.getComponentType) <:< implicitly[reflect.ClassTag[A]]
^
它告诉我使用TypeTag
。但是如何?这是否是一个有效的反思问题?
附录:这似乎很好地工作为我所需要的,但它并不适用于AnyVal
工作:
scala> def arrayConformsTo[A: reflect.ClassTag](as: Array[_]) =
| implicitly[reflect.ClassTag[A]].runtimeClass isAssignableFrom as.getClass.getComponentType
太棒了!如果你不介意,我会在接受它之前编辑你的答案以提供另一个解决方案 –