Question

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?

Was it helpful?

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.

OTHER TIPS

I'd like to say that you can use a type alias:

type HasFooMethod = { def foo: String }
val v = new Object {def foo = "bar"}
v.isInstanceOf[HasFooMethod]

But that'll always return true, thanks to erasure.

So you can either use reflection, or just try and pass the object to a method taking a structural type as a parameter - the compiler will then error if it's not valid.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top