3 ms·
Honestly I think the "val vs var" debate is kind of a misdirection. The real difficulty with mutability comes from interior mutability. The scala standard libra
by nicopappl 6y ago
Honestly I think the "val vs var" debate is kind of a misdirection. The real difficulty with mutability comes from interior mutability. The scala standard library has collection.mutable.{List, Map, Set, etc.} and collection.immutable.{List, Map, Set, etc.} with collection.immutable being the one in the prelude (imported by default). In scala like any ML language that supports mutability, you can do
val immutableValue = mutable.Map.empty
immutableValue.insert(key, value)
In this case the distinction between "val" and "var" is at best a misdirection. The only language that I know of that explicits interior mutability is rust. Where your map must have a "type marker" `&mut` to be able to use the `insert` method. The only way to have that type marker is to define the map with a `let mut`:
let clearlyImmutable: Map<String, Int> = Map::new()
clearlyImmutable.insert("hello", 10) // Does not compile
while
let mut clearlyMutable: Map<String, Int> = Map::new()
clearlyMutable.insert("hello", 10) // Compiles :)
The conclusion here is that if you are not working with rust, immutable data structures (where no method mutates the object it refers to) are what guarantees you you won't run into spooky mutability at a distance.
However, it would be disingenuous to not mention that you can run very quickly in the wild into scala code that is just "java without semicolons". You can very deliberately break null safety in scala. For example `val x: (Int, Double) = null` does compile. You won't normally run into `null` unless you are interacting with java libs or with code from programmers who don't understand type safety.
I want to point out: scala let you do all those nasty things, but this will be a deliberate choice. The mutable data structure from the standard library are clearly marked. There is no methods in the standard library that returns null (outside of regex methods which are thin wrappers around java regexes). Writing mutable code requires a completely different architecture and design choices. If you are in an immutable team, it will be very hard to justify that kind of code. While in a mutable team, the reverse might be true.
- CodesInChaos 6y agoYour rust example isn't considered interior mutability, since it needs `&mut`. Since `&mut` references are exclusive, they're quite similar to immutable values in functional languages, despite the API appearing mutable. In Rust the 'interor mutability' term is used for types like `Mutex`/`RefCell`, `Cell`, or atomics, which are mutable even through shared references. These come with the same problems as interor mutability in scala.