从 Any 到 Dynamic 的隐式转换
为什么以下不起作用? (是的,我正在使用2.9.0final并打开了“-Xexperimental”选项。)
implicit def any2Dynamic(a: Any) = new Dynamic {
def applyDynamic(name: String)(args: Any*) = {
println(a + name)
}
}
"Say".hello // value hello is not a member of java.lang.String
人们可以争论这有多么有意义......如果这可行的话正如预期的那样,"Say".toInt
的优先级为:StringLike.toInt
或 (new Dynamic {...}).applyDynamic("toInt" )
?
Why isn't the following working? (Yes, I am working with 2.9.0final and turned the "-Xexperimental" option on.)
implicit def any2Dynamic(a: Any) = new Dynamic {
def applyDynamic(name: String)(args: Any*) = {
println(a + name)
}
}
"Say".hello // value hello is not a member of java.lang.String
One can argue about how meaningful this is... If this would work as expected what precedence will take place at "Say".toInt
: StringLike.toInt
or (new Dynamic {...}).applyDynamic("toInt")
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先编译器 查找来自
String => 的隐式视图{ def 你好:? }
。失败了,所以它 检查是否String <: Dynamic
。这些没有合并。这个动态应用功能尚未最终确定——在 Scala 2.9.0 中它是实验性的,可能会发生变化。但我怀疑这是否会被包括在内,因为有了这样的隐式,你就把所有类型安全都扔到了窗外。您永远不会因为拼写错误的方法名称或不正确的参数类型而收到编译错误。您的用例是什么?
The compiler first looks for an implicit view from
String => { def hello: ? }
. That fails, so it then checks ifString <: Dynamic
. These are not combined.This dynamic apply feature has not been finalized -- in Scala 2.9.0 it is experimental, and subject to change. But I doubt this would be included, as with such an implicit, you throw all type safety out the window. You would never get a compile error for misspelled method names or incorrect argument types. What is your use case?