【发布时间】:2010-10-22 22:12:23
【问题描述】:
我希望能够写出类似的代码
10 times {
doSomething
}
所以我想我可以用隐式来做到这一点。
当我在 Scala REPL 中执行以下代码时,它会被正确定义
scala> implicit def intToMyRichInt(count: Int) = {
| new {
| def times(f: => Unit) = {
| 1 to count foreach { _ => f }
| }
| }
| }
但是当我尝试编译时,
object Test {
implicit def intToMyRichInt(count: Int) = {
new {
def times(f: => Unit) = {
1 to count foreach { _ => f }
}
}
}
错误提示失败
error: recursive method intToMyRichInt needs result type
1 to count foreach { _ => f }
有什么区别?我做错了什么?
【问题讨论】:
-
times的正文后缺少的}是复制粘贴错误?因为,除此之外,它在这里编译得很好。
标签: scala dsl anonymous-class higher-order-functions implicits