1

I start to learn scala by writing simple code.

I'm a little confused about the behavior of below code.

class BasicUsage {
  private val incr = (x: Int) =>
    {
      println("incr invoked")
      x + 1
    }
  private val add = (x: Int, y: Int) =>
    {
      println("add invoked")
      if (x == 0 || y == 0) {
        0
      } else {
        x + y
      }
    }

  def testFuns(): Unit =
    println(add(1,2))
    println(incr(5))

}

When invoking testFuns(), the output is as below,

incr invoked

6

add invoked

3

Per my understanding, functions add() should be called firstly, then incr() should be invoked.

What's the mistake in above code? Do I misunderstand the usage of function and method?

Thanks very much,

1 Answer 1

4

You're missing curly braces in your testFuns method:

def testFuns(): Unit =
  println(add(1,2))
  println(incr(5))

This means that testFuns() contains only one first statement: println(add(1,2)). The second statement belongs to class and gets executed once BasicUsage instantiated. To fix it do:

def testFuns(): Unit = {
  println(add(1,2))
  println(incr(5))
}
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, you're right. My problem resolved. I mixed the scala usage with python.
Usually the braces are optional because the compiler can infer where the function returns, but the compiler is hunting for a Unit type and got one immediately on println(add(1,2)) and determined that was the end of the function. What you wrote was equivalent to: def testFuns(): Unit = println(add(1,2)); println(incr(5))
"Usually the braces are optional because the compiler can infer where the function returns, but the compiler is hunting for a Unit type and got one immediately" No, this is completely wrong. This part happens long before types are considered. Without braces, only one expression is used as the body of the function (actually, with braces too; it's just that braces here are Scala syntax for turning a sequence of expressions into a single expression).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.