Changda Li
Changda Li

Reputation: 23

scala: error: recursive value needs type

I'm trying to write a short snippet of scala code to understand parenthesesless method and postfixOps.
Here is my code:

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
        }
    }

}

However, while compiling it, I have a problem says:

error: recursive value tomAge needs type
        println(tomAge)

If I replace the method call person getAge to person.getAge, the program will run correctly.
so why the function call of person getAge failed?

Upvotes: 2

Views: 7739

Answers (2)

developer_hatch
developer_hatch

Reputation: 16224

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

Your code does't work because you need to add the ";" in the infix operations!

I tryed your example here and worked just fine!

See this answer, the accepted answer shows another example

Upvotes: 1

Leo C
Leo C

Reputation: 22449

Postfix notation should be used with care - see sections infix notation and postfix notation here.

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.

Your code will work (with a compiler warning) if you append a ; to val tomAge = person getAge.

Upvotes: 6

Related Questions