Why doesn't scala have C++-like const-semantics?

Viewed 2195

In C++. I can declare most things as const, for example:
Variables: const int i=5;
Scala has val i=5, however this will only prevent reassigning, not changing the object as the following exampe shows:
C++:

const int i[]={1,2,3,4};
i[2]=5; //error
Scala:
val a=Array(1,2,3,4)
a(2)=5 //a is now Array(1, 2, 5, 4)

It gets even worse with member functions:
C++:

class Foo {
int i;
int iPlusFive() const {return i+5;}
int incrementI(){ return ++i; }
}
I can be sure, that calling iPlusFive won't change the object and that I won't accidentally call incrementI on a const object.

When it comes to collections, C++ continues it's const-correct streak with const collections: simply declare your vector as const and you can't change it. Assign a non-const vector<Int> to a const vector<Int> and the compiler won't copy anything and will prevent you from changing anything in the now const collection.

Scala has scala.collection.mutable.whatever and scala.collection.immutable.whatever, you can't just convert mutable collections to immutable collections, furthermore you're still allowed to change the collected objects with their non-const member functions.

Why does scala, which has an otherwise really great type-system, not have anything comparable to C++ const-keyword?

Edit: Margus suggested using import scala.collection.mutable. My solution was to use

import scala.collection.mutable.HashMap
import scala.collection.immutable.{HashMap => ConstHashMap}
This will make the mutable HashMap available as HashMap and the immutable als ConstHashMap, however I still like the C++ approach better.

4 Answers
Related