我被告知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)
Run Code Online (Sandbox Code Playgroud)
为什么需要new关键字REPEAT功能?
new { def ...}构造创建一个具有结构类型的 AnyRef{def ...}新匿名对象:
scala> val aa = new { def kk = "bb" }
aa: AnyRef{def kk: String}
Run Code Online (Sandbox Code Playgroud)
UNTIL由于名为“结构类型成员的反射访问”的功能,您的方法是可访问的import scala.language.reflectiveCalls,并且由于SIP 18:模块化语言功能,您还应该至少在 Scala 2.11.2 中拥有一个:
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
Run Code Online (Sandbox Code Playgroud)
请注意,它比定义要慢一点class Repeatable {def UNTIL = ...},因为(对于 JVM)您的REPEAT函数只是返回Object(AnyRef) 并且没有可以从中转换的类型,因此 ScalaUNTIL使用反射进行调用。它也没有引入一些合成类,因为结构类型可以匹配任何现有的类(具有适当UNTIL方法的任何其他类)。
| 归档时间: |
|
| 查看次数: |
113 次 |
| 最近记录: |