scala – 为什么模拟UNTIL / REPEAT的代码需要新的关键字?
发布时间:2020-12-16 18:36:04 所属栏目:安全 来源:网络整理
导读:我被告知 Scala提供了对UNTIL,REPEAT控制流程建模的能力. 在研究能力时,我找到了代码: // ref: https://gist.github.com/metasim/7503601def REPEAT(body: = Unit) = new { def UNTIL(condition: = Boolean): Unit = { body if (condition) () else UNTIL(c
我被告知
Scala提供了对UNTIL,REPEAT控制流程建模的能力.
在研究能力时,我找到了代码: // ref: https://gist.github.com/metasim/7503601 def REPEAT(body: => Unit) = new { def UNTIL(condition: => Boolean): Unit = { body if (condition) () else UNTIL(condition) } } // test code REPEAT { x = x + 1 } UNTIL (x > 3) 为什么需要REPEAT函数中的new关键字? 解决方法
new {def …}构造用
structural type AnyRef {def …}创建一个新的匿名对象:
scala> val aa = new { def kk = "bb" } aa: AnyRef{def kk: String} 您的UNTIL方法是可访问的,因为称为“结构类型成员的反射访问”,您还应该有一个导入scala.language.reflectiveCalls,至少在Scala 2.11.2中作为SIP 18: Modularizing Language Features的结果: scala> aa.kk <console>:9: warning: reflective access of structural type member method kk should be enabled by making the implicit value scala.language.reflectiveCalls visible. This can be achieved by adding the import clause 'import scala.language.reflectiveCalls' or by setting the compiler option -language:reflectiveCalls. See the Scala docs for value scala.language.reflectiveCalls for a discussion why the feature should be explicitly enabled. aa.kk ^ res0: String = bb 注意,它比定义类Repeatable {def UNTIL = …}慢一点,因为(对于JVM)你的REPEAT函数只返回Object(AnyRef),并且没有可以从中强制转换的类型,因此Scala使用UNTIL调用UNTIL反射.它也没有引入一些合成类,因为结构类型可以匹配任何现有的类(任何其他具有适当UNTIL方法的类). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |