Question

I am learning Scala as a personal interest and I'm perplexed by the return value of the following, of which I expect to eventually print 52:

def lexicalTest(a: Int) = {
  (b: Int) => {
    (c: Int) => {
        a + b + c
    }
  }
}

val step01 = lexicalTest(10)

val step02 = step01(10)


def plusThirty(a: Int, b: Int) {
  a + b
}

println(plusThirty(22, step02(10)))

If step02(10) surely returns 30, and it is of type Int, then why is my return equal to ()

FWIW: I am coming from the perspective of getting this kind of thing to work in JavaScript.

UPDATE: Thanks cookie monster, def plusThirty(a: Int, b: Int) { should read def plusThirty(a: Int, b: Int) = {

Was it helpful?

Solution

In scala, As per §4.6 from reference if you declare below function:

def f(n:Somthing) = {}

Then the return type of f unless manually specified is taken (thanks to type inference) from the return type the block returns.

As per §4.6.3, the below is a procedure

def f(n:Somthing) {}

Where the return type of fis Unit even though it appears as Int. Infact if you manually use return rather than from implicit return, in repl it gives:

scala> def plusThirty(a: Int, b: Int) {
     |  return a + b
     | }
<console>:8: warning: enclosing method plusThirty has result type Unit: return value discarded
        return a + b
        ^
plusThirty: (a: Int, b: Int)Unit

scala> plusThirty(22, step02(10))

So as said in comments, it should be below else it would had been a procedure:

def plusThirty(a: Int, b: Int)  = {
  a + b
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top