Question

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!

Was it helpful?

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.

OTHER TIPS

| a b |
a := b := 'foo'.
a == b. "=> true, so the identical string"
a at: 1 put: $b.
b "=> 'boo'

So in Squeak, and probably in Pharo, string literals are not immutable.

Other Smalltalks do support immutability, so perhaps string literals in those Smalltalks are indeed immutable.

Regarding copying, perhaps you're carrying assumptions over from other languages. 'foo' is a literal in the sense that there's syntax for creating a String, but really, 'foo' is just another object. In Squeak and Pharo these literals are just normal String instances, and so you are free to mutate them.

As the above snippet shows, that can lead to unexpected results, because if you change the first line to a := 'foo'. b := 'foo'. you still end up with the same result: Squeak quietly shares that literal, rather than making a new one with the same value.

The book is wrong. In squeak, strings are not immutable. Which book is that?

'zero' at: 1 put: $h; yourself. => 'hero'

'zero' copy at: 1 put: $h; yourself => 'hero'

Characters are immutable though. It would be funny if they weren't.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top