You know this scene in Goodbye and Thanks to everyone for the fish, where Arthur is so insanely happy that he stops the waiter and demands to know: "Why is this food so good?" I am in such a situation. Scala seems to be doing what I want, but I don’t understand how this is done. Consider the following:
scala> var v = Nil:List[String]; v: List[String] = List() scala> v.length res38: Int = 0 scala> v ::= "Hello" scala> v.length res39: Int = 1 scala> Nil.length res40: Int = 0
This is exactly what you hope for, but how does it happen?
Nil is an object that extends List [Nothing], which is a subtype of List [String], so the assignment works fine, but it's an immutable list, isn't it? Therefore, I could not add it. But I can add to it, or at least I can add to v, which I thought points to Neil. v is changing, but Nil is not.
So, WTF? Does Scala have any clever copy-on-modification semantics that I don't know about? Is Nil really a function that returns empty lists? More broadly, is there any way to get the REPL to answer these questions?
scala
Malvolio
source share