Assume, we have an abstract class with an abstract type field:
abstract class A {type T}
Now let's assume, we have a method, which returns objects of type A
, but the type field T
may differ. How can we distinguish between these objects ?
We can try a pattern match:
object Test {
def tryToDistinguish(a: A) =
a match {
case b: A {type T = String} => println("String type")
case b: A {type T = Int} => println("Int type")
case b: A => println("Other type")
}
}
But the compiler will complain:
$>scalac -unchecked Test.scala
Test.scala:8: warning: refinement example.test.A{type T = String} in type patter
n example.test.A{type T = String} is unchecked since it is eliminated by erasure
case b: A {type T = String} => println("String type")
^
Test.scala:9: warning: refinement example.test.A{type T = Int} in type pattern e
xample.test.A{type T = Int} is unchecked since it is eliminated by erasure
case b: A {type T = Int} => println("Int type")
^
two warnings found
It seems the type of the type field will be removed by erasure (side question: Because type fields are translated to parameter types in Java ?)
Therefore, this will not work:
scala> Test.tryToDistinguish(new A {type T = Int})
String type
Alternative : We can alternativley create an enumeration and put an additional field in the class A
in order to distinguish the objects. But this smells, because it would mean, that we re-implement the type system.
Question : Is there a way to differ between the types of the objects with the help of the type field ? And if not, what will be a good workaround ?