문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top