关于Scala:如何查找对象的运行时实例?

 2021-04-27 

How to find runtime instance of an object?

如何查找REPL中fruitBasket是否包含Orange

1
2
3
4
class MyContainer[+A](val a: A)
class Fruit
class Orange extends Fruit
val fruitBasket: MyContainer[Fruit] = new MyContainer[Orange](new Orange())

通常,如果我为超类变量分配了子类对象,如何检查/打印该变量的运行时实例?


该类型已被强制转换为"水果",但您可以在内容上进行模式匹配:

1
2
3
4
5
6
7
8
9
10
11
scala> fruitBasket
res11: MyContainer[Fruit] = MyContainer@2986db02

scala> fruitBasket.a
res12: Fruit = Orange@5d9515d6

scala> fruitBasket.a match {
         case o: Orange => println("orange")
         case _ => println("not orange")
       }
orange

您可以使用getClass进行连接:

1
2
3
4
5
scala> fruitBasket.a.getClass
res21: Class[_ <: Fruit] = class Orange

scala> fruitBasket.a.getClass.toString
res22: String = class Orange