What are some example use cases for symbol literals in Scala?

In Java terms, symbols are interned strings. This means, for example, that reference equality comparison (eq in Scala and == in Java) gives the same result as normal equality comparison (== in Scala and equals in Java): 'abcd eq 'abcd will return true, while "abcd" eq "abcd" might not, depending on JVM’s whims (well, it should for literals, but not for strings created dynamically in general).

Other languages which use symbols are Lisp (which uses 'abcd like Scala), Ruby (:abcd), Erlang and Prolog (abcd; they are called atoms instead of symbols).

I would use a symbol when I don’t care about the structure of a string and use it purely as a name for something. For example, if I have a database table representing CDs, which includes a column named “price”, I don’t care that the second character in “price” is “r”, or about concatenating column names; so a database library in Scala could reasonably use symbols for table and column names.

Leave a Comment