如何确定 Scala 中对象的类?

Jav*_*ide 5 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)
Run Code Online (Sandbox Code Playgroud)

Mic*_*jac 3

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

import scala.reflect.runtime.universe._

def tpeOf[A](a: A)(implicit tt: TypeTag[A]): Type = tt.tpe
Run Code Online (Sandbox Code Playgroud)

以及一些示例类:

class Foo
class Bar extends Foo
val x = new Foo
val y = new Bar
Run Code Online (Sandbox Code Playgroud)

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

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

但这不适用于特征,因为在您的示例中y不是实例,它是扩展bar的匿名类的实例。所以使用这种方法总是会产生效果。 barfalse

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