How to distinguish between objects with different abstract type fields?

前端 未结 3 1465
天命终不由人
天命终不由人 2021-01-15 21:58

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

3条回答
  •  [愿得一人]
    2021-01-15 22:04

    side question: Because type fields are translated to parameter types in Java ?

    There are no type parameters in bytecode, so type fields could not possibly be translated into them. Type fields only exist during compilation.

    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.

    There's only one kind of type question you can make at run time: what class is this? Scala 2.10 gives a bit more information, but it still boils down to that question.

    If you actually subclass A, you can get that information through reflection (on 2.10). Otherwise, I don't think so -- I've tested on REPL, and there it doesn't work, but things compiled to class files have more information on them.

    Any other question has to be made about values.

    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 ?

    No, unless Scala 2.10, reflection, and subclasses. Good workaround? Use values. The usual way to handle it is not enumeration, though, but Manifest, which can be generated implicitly.

    Look up questions about how to get around type erasure in Scala.

提交回复
热议问题