如果我有一個方法...如何使用新的反射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
太棒了!如果你不介意,我會在接受它之前編輯你的答案以提供另一個解決方案 –