如何确定Scala中对象的类?

时间:2015-05-03 20:11:15

标签: scala subclass instanceof subtyping

我需要检查 y 是否是 bar 的实例,而不是 foo 。我怎么能在Scala中做到这一点?

trait foo {}

trait bar extends foo {}

val x = new foo {}
val y = new bar {}

x.isInstanceOf[foo] // true
x.isInstanceOf[bar] // false

y.isInstanceOf[bar] // true
y.isInstanceOf[foo] // true (but I want it to return false)

2 个答案:

答案 0 :(得分:3)

如果您只是创建新实例,

getClass将起作用。但是你正在创建新的匿名类和实例。

对于那些与foo和bar的关系完全相同:它们是超类。

答案 1 :(得分:3)

你问题的标题是课,但实际的问题是使用特征。您可以通过 classes 的运行时反射来执行此类操作。让我们创建一个方便的方法来获取对象的reflect.runtime.universe.Type

import scala.reflect.runtime.universe._

def tpeOf[A](a: A)(implicit tt: TypeTag[A]): Type = tt.tpe

以及一些示例类:

class Foo
class Bar extends Foo
val x = new Foo
val y = new Bar

我们可以使用tpeOf方法获取Type xy,并将其与Type TypeTag进行比较使用typeOf获得。这将产生您想要的结果。

scala> tpeOf(x) =:= typeOf[Foo]
res0: Boolean = true

scala> tpeOf(x) =:= typeOf[Bar]
res1: Boolean = false

scala> tpeOf(y) =:= typeOf[Foo]
res2: Boolean = false

scala> tpeOf(y) =:= typeOf[Bar]
res3: Boolean = true

但这不适用于特征,因为在您的示例中y 不是 bar的实例,它是一个匿名类的实例, 扩展 bar。因此,使用此方法总是会产生false

trait foo {}
trait bar extends foo {}
val x = new foo {}
val y = new bar {}

scala> tpeOf(x) =:= typeOf[bar]
res4: Boolean = false   // As expected, `x` is not exactly `bar`
相关问题