The use of symbol literals is not immediately clear from what I've read up on Scala. Would anyone care to share some real world uses?
Is there a particular Java idiom being covered by symbol literals? What languages have similar constructs? I'm coming from a Python background and not sure there's anything analogous in that language.
What would motivate me to use 'HelloWorld vs "HelloWorld"?
Thanks
Symbols are used where you have a closed set of identifiers that you want to be able to compare quickly.
A symbol literal 'x is a shorthand for the expression scala. Symbol("x") . Symbol is a case class, which is defined as follows. package scala final case class Symbol private (name: String) { override def toString: String = "'" + name }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With