|
Re: Symbol literals?
|
Posted: Sep 9, 2008 9:41 AM
|
|
HI Vladimir,
Sorry, I think our examples are a bit too contrived here. Basically the most significant difference between a symbol literal and a string literal is that you can't have spaces in a symbol literal. You also can't have spaces in Scala identifiers, like method names, variables names, class names, etc. That's really the main thing they are intended to be used for, as far as I know.
A use case for symbols is if you are trying to do something dynamic in a Scala program. For example, perhaps you define a method that is supposed to take as one argument the name of another method. It is better to pass a symbol in for the method name rather than a string for two reasons. One reason is the syntax looks a bit less cumbersome on the invocation, because you have one tick mark in front of the method name string being passed, rather than needing to surround it with double quotes on both ends. Another is that if you change a method name using a refactoring IDE or other refactoring tool, that tool could either change all the symbols with that name, or show them to you, etc. It is the kind of heuristic refactoring you get with a dynamic language, but by having those names symbols instead of strings, that should reduce the likelihood of false hits when doing heuristic refactoring.
A concrete example is I'm planning to add a method for invoking private methods to ScalaTest, so that it is easier to test private methods. I can't invoke them statically, because it won't compile (because they are private). I have to use reflection, but that code is very verbose, so I'm making an invokePrivate method to make it less verbose. invokePrivate will take the name of the private method to invoke as a symbol, not a string, for the above reasons.
|
|