How to set a String in a Option[String]?

Scala

Scala Problem Overview


When I'm trying to affect a value of type String in a field of type Option[String] I get the following error :

type mismatch; found : String required: Option[String]

How can I affect value myValue:String into field myField:Option[String] ?

Scala Solutions


Solution 1 - Scala

You can also just use Option(myValue) which will convert null to None and non-null to Some.

Solution 2 - Scala

You can wrap any object in an Option like this:

val opt = Some("foo")

Solution 3 - Scala

You can just wrap your object in Some class

val myField = Some(myValue)

Or if you dont have Anything, pass

None

Its called Option pattern

http://www.codecommit.com/blog/scala/the-option-pattern

Solution 4 - Scala

If you want to convert empty string to None more universal solution is: Option(str).filter(_.nonEmpty)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questioni.am.michielView Question on Stackoverflow
Solution 1 - ScalaChanning WaltonView Answer on Stackoverflow
Solution 2 - ScalaKim StebelView Answer on Stackoverflow
Solution 3 - ScalaFUDView Answer on Stackoverflow
Solution 4 - ScalaRoman KazanovskyiView Answer on Stackoverflow