1

How can I find if fruitBasket contains Orange in REPL?

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

In general, if I assign a subclass object o a superclass variable, how can I check/print the runtime instance of the variable?

Manu Chadha
  • 15,555
  • 19
  • 91
  • 184
  • I think maybe is duplicate of this question? https://stackoverflow.com/questions/19386964/i-want-to-get-the-type-of-a-variable-at-runtime – Andy Hayden Oct 25 '17 at 05:32

1 Answers1

0

The type has been coerced into a Fruit but you can pattern match on the contents:

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

You can reach in using getClass:

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

scala> fruitBasket.a.getClass.toString
res22: String = class Orange
Andy Hayden
  • 359,921
  • 101
  • 625
  • 535