【问题标题】:scala: error: recursive value needs typescala:错误:递归值需要类型
【发布时间】:2017-05-26 23:28:31
【问题描述】:

我正在尝试编写一个简短的 scala 代码 sn-p 来理解无括号方法和 postfixOps。
这是我的代码:

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 getAge替换为person.getAge,程序就可以正常运行了。
那么为什么person getAge的函数调用会失败呢?

【问题讨论】:

    标签: scala recursion


    【解决方案1】:

    后缀表示法应谨慎使用 - 请参阅 infix notationpostfix notation here 部分。

    此样式不安全,不应使用。由于分号是 可选,编译器将尝试将其视为中缀方法,如果 它可以,可能会从下一行取一个术语。

    如果您将; 附加到val tomAge = person getAge,您的代码将正常工作(带有编译器警告)。

    【讨论】:

    • 这是一个很棒的解释!感谢分享,我看了你分享的文档,很有帮助!
    • 谢谢,@Damian Lattenero。这是一个相当棘手的“异常”。如果以下 println 代码行没有引用 tomAge,则错误消息 error: Int does not take parameters 会更具启发性。
    • 我试图在网络编译器中找到它,你只是发表评论,它很棒
    • 感谢您的清晰解释和有用的文档!
    【解决方案2】:
    def main(args: Array[String]) {
        val person = new Person("Tom", 10);
        val tomAge = person getAge; ///////////
        println(tomAge)
    }
    

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

    我尝试了您的示例 here 并且工作得很好!

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

    【讨论】:

    • @Changada Li!极好的!没问题,我一直很喜欢帮忙,当我回答另一个朋友时,我先回答了哈哈哈,但好吧……很高兴能提供帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 2012-11-09
    • 1970-01-01
    • 1970-01-01
    • 2011-04-13
    相关资源
    最近更新 更多