0

I'm trying to understand the differences between these 2 syntaxes in scala and why they have not the same result.

testVal

and

testVal2

are not defined in the same way

object FunctionVsVal2 extends App {


  val testVal: () => Int = {
    val r = util.Random.nextInt
    () => r
  }

  val testVal2: () => Int = () => {
    val r = util.Random.nextInt
    r
  }

  println(testVal())
  println(testVal())

  println(testVal2())
  println(testVal2())
}

Thanks

1 Answer 1

4

testVal2 is a lambda expression. Each time you call testVal2(), it evaluates

{
  val r = util.Random.nextInt
  r
}

and so returns a new value.

testVal is a block expression. It calculates r first and then returns () => r (the last expression in the block), so each time you call testVal(), the same r is used.

Sign up to request clarification or add additional context in comments.

3 Comments

if testVal2 is called each time why : println(testVal2 eq testVal2) prints true ? I was expecting to be false
testVal2 eq testVal2 checks that testVal2 is the same object as testVal2. Why do you expect it not to be? It's unrelated to what happens when you apply testVal2 by writing testVal2().
In both cases the body of the lambda, the part after () =>, is called each time you call testVal1/2(). The difference is what these bodies are; in testVal1 it's just r, in testVal2 it's { val r = util.Random.nextInt; r }. Does this help more?

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.