Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy doesn't scala have C++-like const-semantics?
    primarykey
    data
    text
    <p>In C++. I can declare most things as const, for example:<br> Variables: <code>const int i=5;</code><br> Scala has <code>val i=5</code>, however this will only prevent reassigning, not changing the object as the following exampe shows:<br> C++: <pre><code>const int i[]={1,2,3,4}; i[2]=5; //error</code></pre> Scala: <pre><code>val a=Array(1,2,3,4) a(2)=5 //a is now Array(1, 2, 5, 4)</pre></code></p> <p>It gets even worse with member functions:<br> C++: <pre><code>class Foo { int i; int iPlusFive() <b>const</b> {return i+5;} int incrementI(){ return ++i; } }</pre></code> I can be sure, that calling iPlusFive won't change the object and that I won't accidentally call incrementI on a const object.</p> <p>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 <code>non-const vector&lt;Int&gt;</code> to a <code>const vector&lt;Int&gt;</code> and the compiler won't copy anything and will prevent you from changing anything in the now const collection.</p> <p>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.</p> <p>Why does scala, which has an otherwise really great type-system, not have anything comparable to C++ const-keyword?</p> <p><b>Edit: </b> Margus suggested using <code>import scala.collection.mutable</code>. My solution was to use <pre><code>import scala.collection.mutable.HashMap import scala.collection.immutable.{HashMap => ConstHashMap}</code></pre> This will make the mutable HashMap available as HashMap and the immutable als ConstHashMap, however I still like the C++ approach better.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload