A Story of ‘Symbol
A somewhat secret and powerful construct is Scala’s Symbol class. Symbols are much alike Strings but have a few key differences. Let’s start with instantiation.
I want one. Gimme, Gimme, Gimme!
You want a Symbol, but you don’t know how. Well, there are two ways. It’s deprecated, and no longer supported in Scala 3, but you can use the Symbol literal syntax, like this:
scala> 'symbol
res0: Symbol = 'symbol
Why do we have this? It’s short. That’s really it. It’s limited in the characters you can use, and it can’t be instantiated dynamically. How can we do this more idiomatically? Good ol' class construction:
scala> Symbol("A Symbol w/ Spaces :)")
res1: Symbol = 'A Symbol w/ Spaces :)
Now, we have our Symbols.
I Thought Strings were Enough?
They are, in most cases, but Symbols are special. We need to talk about String interning. String interning is designed to help you save memory if have many equivalent Strings in your application
If you intern a String, it will be placed in the intern pool on the JVM where it. A reference to that String will be used instead of a new instance every time it’s called. This is particularly useful for fast equality checking, as it only needs to check if the references are equal. Note: String interning always occurs for compile-time Strings.
That brings us back to Symbols. Symbols are interned are Strings. The difference between Symbols and normal Strings is that Symbols have faster equality checking.
领英推荐
But, when is it Worth It?
Whenever you’re comparing the same set of Strings over and over again, for example, a map with String keys.
Perhaps instead of:
Map[String, Any]
It might be time for:
Map[Symbol, Any]
There are lots of use-cases. Keep an eye out, but not before reading the next section.
When not to use Symbol:
Symbols do come with disadvantages. For one, interning is an expensive process, so only utilize it when you really have to. Secondly, interned Strings live in the PermGen space. If you’re not careful you can run out of memory, even if you have plenty of heap space.
Be careful, be smart, and use Symbols when they improve the quality of your programs. Now, go build something awesome.
Regards,
Bradly O
Functional Scala Programmer
2 年Make sure to follow The Scala Developer.