How to set a String in a Option[String]?
ScalaScala 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
Solution 4 - Scala
If you want to convert empty string to None more universal solution is: Option(str).filter(_.nonEmpty)