如何知道对象是否是 TypeTag 类型的实例? [英] How to know if an object is an instance of a TypeTag's type?
问题描述
我有一个函数可以知道一个对象是否是Manifest
类型的一个实例.我想将其迁移到 TypeTag
版本.旧函数如下:
I have a function which is able to know if an object is an instance of a Manifest
's type. I would like to migrate it to a TypeTag
version. The old function is the following one:
def myIsInstanceOf[T: Manifest](that: Any) =
implicitly[Manifest[T]].erasure.isInstance(that)
我一直在试验 TypeTag,现在我有了这个 TypeTag 版本:
I have been experimenting with the TypeTags and now I have this TypeTag version:
// Involved definitions
def myInstanceToTpe[T: TypeTag](x: T) = typeOf[T]
def myIsInstanceOf[T: TypeTag, U: TypeTag](tag: TypeTag[T], that: U) =
myInstanceToTpe(that) stat_<:< tag.tpe
// Some invocation examples
class A
class B extends A
class C
myIsInstanceOf(typeTag[A], new A) /* true */
myIsInstanceOf(typeTag[A], new B) /* true */
myIsInstanceOf(typeTag[A], new C) /* false */
有没有更好的方法来完成这个任务?是否可以省略参数化的 U
,使用 Any
代替(就像在旧函数中所做的那样)?
Is there any better way to achieve this task? Can the parameterized U
be omitted, using an Any
instead (just as it is done in the old function)?
推荐答案
如果对已擦除的类型使用子类型检查就足够了,请按照 Travis Brown 在上面评论中的建议进行操作:
If it suffices to use subtyping checks on erased types, do as Travis Brown suggested in the comment above:
def myIsInstanceOf[T: ClassTag](that: Any) =
classTag[T].runtimeClass.isInstance(that)
否则你需要明确地拼出 U
类型,以便 scalac 在一个类型标签中捕获它的类型:
Otherwise you need to explicitly spell out the U
type, so that scalac captures its type in a type tag:
def myIsInstanceOf[T: TypeTag, U: TypeTag] =
typeOf[U] <:< typeOf[T]
这篇关于如何知道对象是否是 TypeTag 类型的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!