Scala Symbol Literals
Examples
Replacing strings in case clauses
Let's say we have multiple data sources which include database, file, prompt and argumentList. Depending on chosen source we change our approach:
def loadData(dataSource: Symbol): Try[String] = dataSource match {
case 'database => loadDatabase() // Loading data from database
case 'file => loadFile() // Loading data from file
case 'prompt => askUser() // Asking user for data
case 'argumentList => argumentListExtract() // Accessing argument list for data
case _ => Failure(new Exception("Unsupported data source"))
}
We could have very well used String in place of Symbol. We didn't, because none of strings's features are useful in this context.
This makes the code simpler and less error prone.