如何在 isInstanceOf 调用中使用结构类型?
标题基本上已经说明了这一点。
有没有办法在 isInstanceOf[
调用中使用例如 new Object {def foo = "bar"}
的类型?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
结构类型不适用于
isInstanceOf
。同样,结构类型的模式匹配是没有意义的(它们总是匹配)。这通常归咎于类型擦除,但即使没有擦除,它也不起作用,因为 JVM 不理解结构类型。
另一方面,Scala 可能足够聪明,可以通过擦除来进行结构类型检查。
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.
我想说你可以使用类型别名:
但是由于擦除,它总是返回 true。
因此,您可以使用反射,或者只是尝试将对象传递给采用结构类型作为参数的方法 - 如果它无效,编译器将出错。
I'd like to say that you can use a type alias:
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.