Using Scala, in a Play 2.0 project, I am trying to grab data from a config file.
At present I use the following code to extract a String:
val foo = Play.current.configuration.getString("foo")
I had expected to get a String object back, but instead an Option[String] object is returned.
I cannot find any Java docs describing the Option[T] object and calling the toString() returns Some( foo ).
The same happens when using the configuration methods to extract Boolean and Int values from the config – ie, Option[Boolean] and Option[Int] are returned.
Can anyone explain what this Option[T] object is and how I can access the value I want in the form that the application method call implies it will be returned?
In scala, the type
Option[T]represents an optional value of the typeT. If you are used to Java terms, you could refer to an Option as ‘a value that might benull‘.In Play they are used when getting the configuration because the string might not be present – if you would try to read it using Java, it would return
null.To get the config string you can use
getOrElse, which lets you provide a default value in case the config string doesn’t exist: