Scala 编译器说我的方法在使用隐式和匿名类时是递归的
我希望能够编写像这样的代码,
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 }
有什么区别?我做错了什么?
I want to be able to write code like
10 times {
doSomething
}
So I thought I could do that with implicits.
When i execute the following code in the Scala REPL it gets defined correctly
scala> implicit def intToMyRichInt(count: Int) = {
| new {
| def times(f: => Unit) = {
| 1 to count foreach { _ => f }
| }
| }
| }
However when i try to compile,
object Test {
implicit def intToMyRichInt(count: Int) = {
new {
def times(f: => Unit) = {
1 to count foreach { _ => f }
}
}
}
it fails with the error
error: recursive method intToMyRichInt needs result type
1 to count foreach { _ => f }
What is the difference? What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
通过删除 def 的 { 来修复代码后,它编译得很好:
还建议删除隐式 def 之后的 {}:
另外,值得一提的是新的 { ... class content ... } 实际上是一种结构类型编译器,因此对 times 的调用将是反射性的。一种解决方法是创建一个新类:
希望能够回答您的问题。
After fix the code by removing the def's {, it compiled just fine:
It's also recommended to remove the {} after the implicit def:
Also, it's worth mentioning the new { ... class content ... } is actually a structural type to compiler, so invocations to times will be made reflectively. One work-around is to create a new class:
Hope to have answered your question.
@tbruhn:我无法验证你的问题,它在这里编译得很好。
我怀疑您可能正在使用某些过时版本的 Scala?
如果是这种情况,明显的解决办法就是升级到 Scala 2.8.x!
不然怎么编译呢?如果您通过 IDE 进行编译,请尝试查看 scalac 是否有相同的错误。
@tbruhn: I could not verify your problem, it compiles fine here.
I suspect that you are using some outdated version of Scala maybe?
If that's the case, the obvious fix is upgrading to Scala 2.8.x!
Otherwise, how do you compile? If you are compiling via your IDE, try to see if
scalac
has the same error.我认为 scala 将无法推断递归函数的返回类型,原因我曾经知道但现在忘记了。
但就你而言,我可以成功编译该文件,只是它又错过了一个}。
I think scala won't be able to infer return types for recursive functions for reasons that I once knew but now forget.
But in your case I can compile the file successfully except it misses one more }.
不幸的是,pedrofurla 建议的解决方法似乎不起作用(至少在 2.8.0 Final 中):
Unfortunately, workaround suggested by pedrofurla doesn't appear to work (at least in 2.8.0 final):