Scala help on Closures

Banashri
Windoof-User
Windoof-User
Beiträge: 25
Registriert: 19. Dez 2013 02:55

Scala help on Closures

Beitrag 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!

leonidglanz
BASIC-Programmierer
BASIC-Programmierer
Beiträge: 126
Registriert: 29. Apr 2015 08:35

Re: Scala help on Closures

Beitrag 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

Banashri
Windoof-User
Windoof-User
Beiträge: 25
Registriert: 19. Dez 2013 02:55

Re: Scala help on Closures

Beitrag von Banashri »

Oh .. I expected sum to be returned from that statement, after addition.

Thank you for the explanation. :-)

Antworten

Zurück zu „Archiv“