Alex Rivera | Logout

Increment (++) operator in Scala

Asked 2010-10-21T22:09:14.700
68

Is there any reason for Scala not support the ++ operator to increment primitive types by default? For example, you can not write:

var i=0
i++

Thanks

Edit
Report

2 Answers

21

In Scala, ++ is a valid method, and no method implies assignment. Only = can do that.

A longer answer is that languages like C++ and Java treat ++ specially, and Scala treats = specially, and in an inconsistent way.

In Scala when you write i += 1 the compiler first looks for a method called += on the Int. It's not there so next it does it's magic on = and tries to compile the line as if it read i = i + 1. If you write i++ then Scala will call the method ++ on i and assign the result to... nothing. Because only = means assignment. You could write i ++= 1 but that kind of defeats the purpose.

The fact that Scala supports method names like += is already controversial and some people think it's operator overloading. They could have added special behavior for ++ but then it would no longer be a valid method name (like =) and it would be one more thing to remember.

answered 2010-10-22T03:17:24.440
0

It isn't included because Scala developers thought it make the specification more complex while achieving only negligible benefits and because Scala doesn't have operators at all.

You could write your own one like this:

class PlusPlusInt(i: Int){
  def ++ = i+1
  }

implicit def int2PlusPlusInt(i: Int) = new PlusPlusInt(i)

val a = 5++
// a is 6

But I'm sure you will get into some trouble with precedence not working as you expect. Additionally if i++ would be added, people would ask for ++i too, which doesn't really fit into Scala's syntax.

answered 2010-10-21T22:23:30.510

Your Answer