Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

syntax

scala

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

like image 326
Joe Holloway Avatar asked Apr 23 '09 04:04

Joe Holloway


People also ask

What is the use of symbol in Scala?

Symbols are used where you have a closed set of identifiers that you want to be able to compare quickly.

What is symbol literal in Scala?

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 }


1 Answers

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.

like image 183
Alexey Romanov Avatar answered Oct 14 '22 18:10

Alexey Romanov