我希望能够编写类似的代码
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 }
有什么区别?我究竟做错了什么?