Search code examples
smalltalksqueak

Are literal strings mutable in smalltalk?


1) What is difference between string and string literal

2) a book says 'zero' at: 1 put: $h will fail because literals are immutable but if I do 'zero' copy at: 1 put: $h works because copying a literal string produces another string which is not a literal. Confused!


Solution

  • Imagine you have a method answering a literal string (literal means whose contents is written literally in source code)

    MyClass>>constantString
        ^'foo'
    

    Now, if this literal string is mutable, you can nastily perform this snippet

    MyClass new constantString at: 1 put: $b.
    

    Then every instance of MyClass will answer 'boo' to #constantString. Though, you can't understand why, because the source code still indicates 'foo'. Nasty...

    Some Smalltalk dialects make those literal string immutable to avoid such accidental bad surprise. Some don't have virtual machine support for immutability and let the entire responsibility to the user.