相关疑难解决方法(0)

如何知道对象是否是TypeTag类型的实例?

我有一个函数,它能够知道一个对象是否是一个Manifest类型的实例.我想将它迁移到一个TypeTag版本.旧功能如下:

def myIsInstanceOf[T: Manifest](that: Any) = 
  implicitly[Manifest[T]].erasure.isInstance(that)
Run Code Online (Sandbox Code Playgroud)

我一直在试验TypeTags,现在我有了这个TypeTag版本:

// 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 */
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来完成这项任务?参数化是否U可以省略,使用Any替代(就像在旧函数中一样)?

scala instanceof scala-2.10

19
推荐指数
2
解决办法
7504
查看次数

使用scala 2.10反射的类型参数的运行时解析

给定一个类型声明,我能够解析类型参数.

scala> reflect.runtime.universe.typeOf[List[Int]] match {case x:TypeRef => x.args}
res10: List[reflect.runtime.universe.Type] = List(Int)
Run Code Online (Sandbox Code Playgroud)

对于运行时值,相同的方法不起作用.

scala> reflect.runtime.currentMirror.reflect(List(42)).symbol.toType match {case x:TypeRef => x.args}
res11: List[reflect.runtime.universe.Type] = List(B)
Run Code Online (Sandbox Code Playgroud)

有没有办法克服反射值的类型擦除?

reflection scala type-erasure scala-2.10

7
推荐指数
1
解决办法
2299
查看次数

标签 统计

scala ×2

scala-2.10 ×2

instanceof ×1

reflection ×1

type-erasure ×1