Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing and getting value

Tags:

scala

Simple scala question. Consider the below.

scala> var mycounter: Int = 0;
mycounter: Int = 0

scala> mycounter += 1

scala> mycounter
res1: Int = 1

In the second statement I increment my counter. But nothing is returned. How do I increment and return something in one statement.

like image 791
dublintech Avatar asked Feb 10 '13 12:02

dublintech


1 Answers

Using '+=' return Unit, so you should do:

{ mycounter += 1; mycounter }

You can too do the trick using a closure (as function parameters are val):

scala> var x = 1
x: Int = 1

scala> def f(y: Int) = { x += y; x}
f: (y: Int)Int

scala> f(1)
res5: Int = 2

scala> f(5)
res6: Int = 7

scala> x
res7: Int = 7

BTW, you might consider using an immutable value instead, and embrace this programming style, then all your statements will return something ;)

like image 57
Alois Cochard Avatar answered Sep 24 '22 13:09

Alois Cochard