1

For example, scalatest says that to check whether an Option is defined or not, I should use an expression like

val opt: Option[String] = ...
opt should be ('defined)

Since Option has isDefined, this either API design or actually an exotic reference to the said function... but I'd like to know how this works.

Dilum Ranatunga
  • 13,254
  • 3
  • 41
  • 52
  • It's a [symbol](http://daily-scala.blogspot.nl/2010/01/symbols.html). I once asked [what the use](http://stackoverflow.com/questions/1324466/practical-examples-of-using-symbols-in-scala) of this is in Scala, and I'm still not convinced that it's a very useful feature. – Jesper Mar 27 '14 at 19:27
  • It defines a Symbol in Scala. Relevant: http://stackoverflow.com/questions/780287/what-are-some-example-use-cases-for-symbol-literals-in-scala http://stackoverflow.com/questions/1324466/practical-examples-of-using-symbols-in-scala – stan Mar 27 '14 at 19:27
  • @Jesper I think symbols are sort-of Scala version of Erlang atoms. – ghik Mar 27 '14 at 20:16
  • @ghik in fact [clojure's keyword](http://clojure.org/data_structures#Data%20Structures-Keywords) is more closely related to scala symbols -- they have the very same implementation mechanism (interned strings) – om-nom-nom Mar 28 '14 at 09:58

1 Answers1

1

Combining the comments to the question and some quick experiments, here's what I've learned:

The syntax 'foo is simply a shortcut for calling a lookup-or-create factory method that returns Symbol instances.

Symbols are not glorified aliases for strings; one cannot simply use a Symbol instance as a String.

Not all strings can be symbols. White spaces, escapes etc are not valid characters in a symbol.

API designers can use these characteristics. In the OP, scalatest's matchers were asking for a function name not as a string, but as a Symbol. They are essentially overloading the be function --

// String; actually AnyRef -- treat as a value comparison
string1 should be ("defined")  

// calls the method on option1 and checks whether output == true
option1 should be ('defined)
Dilum Ranatunga
  • 13,254
  • 3
  • 41
  • 52