Seite 1 von 1

Scala help on Closures

Verfasst: 20. Mai 2015 18:03
von Banashri
Hi,
I am practicing some Scala code related to Closures. I ran the following commands, but some type mismatch error comes up. Can anyone explains me why this error is coming? I declared type everywhere. One thing I noticed is that instead of last line of the method (sum = sum + x), if I pass some Int literal or parameter value, the method gets created.

scala> var sum: Int = 0
sum: Int = 0

scala> def f(x: Int): Int = { println(sum); sum = sum + x }
<console>:8: error: type mismatch;
found : Unit
required: Int
def f(x: Int): Int = { println(sum); sum = sum + x }
^

Thanks in advance!

Re: Scala help on Closures

Verfasst: 20. Mai 2015 18:11
von leonidglanz
Hi,

you have a type error, because you should return an Int at the end.
sum=sum+x does not return an Int.

you could write some thing like that:
def f(x: Int): Int = { println(sum); sum = sum + x; sum }

then you return the Int sum

regards,
Leonid Glanz

Re: Scala help on Closures

Verfasst: 20. Mai 2015 18:32
von Banashri
Oh .. I expected sum to be returned from that statement, after addition.

Thank you for the explanation. :-)