Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get a Some instead of a String in Scala

Tags:

scala

Why do I get a [Some] Object instead of a [String] Object?
The Some object won't work as a String Parameter in a method call.

The config def returns a String so I expect the type to be String.
But when I type "Hello" Scala get's it correct.

Code

    def config(s: String) = Play.current.configuration.getString(s).toString()
    Logger.info(config("recaptcha.publicKey"))
    Logger.info("Hello")

Output

[info] application - Some(6LeDMdASAAAAAC4CFIDY-5M7NEZ_WnO0NO9CSdtj)
[info] application - Hello
like image 781
Farmor Avatar asked Apr 13 '12 22:04

Farmor


People also ask

What does some () mean in scala?

Scala some class returns some value if the object is not null, it is the child class of option. Basically, the option is a data structure which means it can return some value or None. The option has two cases with it, None and Some.

What does ::: mean in scala?

:: - adds an element at the beginning of a list and returns a list with the added element. ::: - concatenates two lists and returns the concatenated list.

What does :+ mean in scala?

On Scala Collections there is usually :+ and +: . Both add an element to the collection. :+ appends +: prepends. A good reminder is, : is where the Collection goes. There is as well colA ++: colB to concat collections, where the : side collection determines the resulting type.

What is string * in scala?

In scala, string is a combination of characters or we can say it is a sequence of characters. It is index based data structure and use linear approach to store data into memory. String is immutable in scala like java.


2 Answers

You are unnecessarily calling toString() on Option[String] (which Play.current.configuration.getString() returns), try this:

def config(s: String) = Play.current.configuration.getString(s).get

or maybe preferably:

Play.current.configuration.getString(s).getOrElse("some default")
like image 190
Tomasz Nurkiewicz Avatar answered Oct 23 '22 15:10

Tomasz Nurkiewicz


getString returns an Option[String], so that it can return an empty value when there is nothing to return. When there is something to return, it returns Some(string) and you can get the inner string using the get() method.

like image 11
Tal Pressman Avatar answered Oct 23 '22 13:10

Tal Pressman