2

Possible Duplicate:
++ operator in Scala

I want to increment an Int variable in scala. But, because Int is immutable, I have to do this

var myInt: Int = 5 .... myInt = myInt + 1 

which seems a little too complicated. What I would like to do is

var myInt: Int = 5 .... myInt++ 

however, since Int is immutable, I can't do this. Is there any solution? Because I can't be first who would want to use ++ on integer variable...

2
  • TL;DR create a custom increment function: def inc(i:Int) = i+1 Commented Jun 16, 2012 at 22:37
  • try scala without var in most vases you won't need it anyway Commented Jun 17, 2012 at 20:20

1 Answer 1

7

A ++ operator is not a language construct of Scala, and the desired behaviour cannot be achieved with a regular method definition. But Scala offers at least some syntactic help, in that a call a += b will be automatically expanded to a = a + b unless a direct method += exists. Thus:

var myInt = 5 myInt += 1 
Sign up to request clarification or add additional context in comments.

1 Comment

a+=1, that's quite enough for me. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.