如何查找对象的运行时实例?

时间:2017-10-25 05:19:14

标签: scala

如何在REPL中找到fruitBasket是否包含Orange

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

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

1 个答案:

答案 0 :(得分:0)

该类型已被强制转换为Fruit,但您可以对内容进行模式匹配:

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:

scala> fruitBasket.a.getClass
res21: Class[_ <: Fruit] = class Orange

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