2

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?

Changda Li
  • 23
  • 1
  • 5

2 Answers2

6

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.

Leo C
  • 22,006
  • 3
  • 26
  • 39
  • that's a fantastic explanaition! Thank's for sharing, I looked the doc you share, very helpful! – developer_hatch May 27 '17 at 00:31
  • Thanks, @Damian Lattenero. It's a rather tricky "anomaly". Had the following `println` code line not been referencing `tomAge`, the error message `error: Int does not take parameters` would have been a little more revelatory. – Leo C May 27 '17 at 01:04
  • I was trying to find it in a web compiler and you just comment and it was great – developer_hatch May 27 '17 at 01:21
  • Thank you for your clear explanation and the helpful doc! – Changda Li May 28 '17 at 01:33
1
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

developer_hatch
  • 15,898
  • 3
  • 42
  • 75
  • @Changada Li! Fantastic! No problem I have always loved to help, when I answered the other pal answered first hahaha but well... Glad to help anyway – developer_hatch May 28 '17 at 01:40