5

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.

dublintech
  • 16,815
  • 29
  • 84
  • 115

3 Answers3

9

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 ;)

Community
  • 1
  • 1
Alois Cochard
  • 9,812
  • 2
  • 29
  • 30
  • Good post. But in my my case I am using a counter which means I can't make it fully immutable. – dublintech Feb 10 '13 at 12:37
  • I'm pretty sure you can, would you mind sharing a pastie with the full use case? – Alois Cochard Feb 10 '13 at 12:39
  • Oh ok, mutating state in actor (seen you comment on other post), then definitely make sense. – Alois Cochard Feb 10 '13 at 12:39
  • did something change in Scala these years? I'm able to do what the OP wasn't able to do when this post was written. EDIT: I'm running "Scala version 2.11.7 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_45)" – asgs May 10 '16 at 18:00
7

Sometimes I do this:

val nextId = { var i = 0; () => { i += 1; i} }
println(nextId())                               //> 1
println(nextId())                               //> 2

Might not work for you if you need sometime to access the value without incrementing.

huynhjl
  • 41,520
  • 14
  • 105
  • 158
1

Assignment is an expression that is evaluated to Unit. Reasoning behind it can be found here: What is the motivation for Scala assignment evaluating to Unit rather than the value assigned?

In Scala this is usually not a problem because there probably is a different construct for the problem you are solving.

I don't know your exact use case, but if you want to use the incrementation it might be in the following form:

(1 to 10).foreach { i => 
  // do something with i
}
Community
  • 1
  • 1
EECOLOR
  • 11,184
  • 3
  • 41
  • 75
  • my exact case is I have an Actor which encapsulates a counter. Every time it is sent a message it increases in value. – dublintech Feb 10 '13 at 12:38
  • I see, that is a good place for a `var`. In that case you might create a method as Alois Cochard suggested: `def increment:Int = { counter += 1; counter }` – EECOLOR Feb 10 '13 at 12:49