2017-05-26 52 views
2

我想写一段简短的scala代码来理解无括号的方法和postfixOps。
这里是我的代码:scala:错误:递归值需要类型

import scala.language.postfixOps 

object Parentheses { 
    def main(args: Array[String]) { 
     val person = new Person("Tom", 10); 
     val tomAge = person getAge 
     println(tomAge) 
    } 


    class Person(val name: String, val age: Int) { 
     def getAge = { 
      age 
     } 
    } 

} 

然而,尽管编译它,我有一个问题说:

error: recursive value tomAge needs type 
     println(tomAge) 

如果我更换方法调用person getAgeperson.getAge,程序将正常运行。
那么为什么函数调用person getAge失败?

回答

4

应谨慎使用Postfix符号 - 请参见infix notationpostfix notationhere节。如果追加;val tomAge = person getAge

This style is unsafe, and should not be used. Since semicolons are optional, the compiler will attempt to treat it as an infix method if it can, potentially taking a term from the next line.

您的代码就可以了(用编译器警告)。

+0

这是一个神奇的解释!感谢分享,我看了你分享的文档,非常有帮助! –

+0

谢谢,@Damian Lattenero。这是一个相当棘手的“异常”。如果下面的'println'代码行没有引用'tomAge',那么错误消息'error:Int不接受参数'会更有启发性。 –

+0

我试图在网页编辑器中找到它,并且您只是发表评论,并且它很棒 –

0
def main(args: Array[String]) { 
    val person = new Person("Tom", 10); 
    val tomAge = person getAge; /////////// 
    println(tomAge) 
} 

您的代码不起作用,因为您需要添加“;”在中缀操作中!

我尝试了你的例子here,工作得很好!

See this answer,接受的答案显示另一个例子

+0

明白了,谢谢! –

+0

@长大李!太棒了!没问题,我一直都很喜欢帮忙,当我回答其他朋友的回答时,第一哈哈哈,但很好...无论如何,很高兴帮助 –