Play2.0 Scala: extract data from a configuration as a string

Using Scala, in a Play 2.0 project, I am trying to capture data from a configuration file.

I am currently using the following code to extract a string:

val foo = Play.current.configuration.getString("foo") 

I expected to return a String object, but an Option[String] object is returned instead.

I cannot find the Java docs describing the Option[T] object, and calling toString() returns Some( foo ) .

The same thing happens when using configuration methods to extract Boolean and Int values ​​from a configuration, i.e. Option[Boolean] and Option[Int] returned.

Can someone explain what this Option[T] object is and how can I access the value that I want in the form that calling the application method implies will be returned?

+4
source share
1 answer

In scala, the type Option[T] represents an optional value of type T If you use Java terms, you can refer to the parameter as "a value that may be null ."

On Play, they are used when retrieving the configuration, because the line may be missing - if you try to read it using Java, it will return null .

To get the configuration line, you can use getOrElse , which allows you to specify a default value if the configuration line does not exist:

 val foo = Play.current.configuration.getString("foo").getOrElse("bar") 
+6
source

Source: https://habr.com/ru/post/1442506/


All Articles