Search code examples
reflectionscalatypesinstanceofstructural-typing

How to use structural types in isInstanceOf calls?


The title basically says it.

Is there a way to use the type of e. g. new Object {def foo = "bar"} in an isInstanceOf[<structural_type_here>] call?


Solution

  • Structural types will not work with isInstanceOf. Likewise, pattern matches to structural types are meaningless (they always match).

    This is usually blamed on type erasure, but even in the absence of erasure it would not work, since JVM does not understand structural types.

    On the other hand, Scala could have been smart enough to make structural type checking work through erasure.