58

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] ?

0

4 Answers 4

84

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

2
  • 3
    You have to understand if you value is equal "" (empty string), option in this case will be Some() Nov 20, 2017 at 11:00
  • 2
    Correct, an empty string is not the same as null. Nov 24, 2017 at 11:15
19

You can wrap any object in an Option like this:

val opt = Some("foo")
2
  • 10
    Note that you should use Option(...) in general to avoid getting a Some(null), as one will usually pass a variable instead of a constant string.
    – Frank
    Jul 30, 2012 at 6:29
  • 1
    also note that if you actually do have a constant string, it is better to use Some("foo")
    – Vic
    Feb 28, 2019 at 23:01
9

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

7

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

2
  • 6
    Option(...) already does everything for you. It replaces null values by None and wraps the others in Some(...). No need to make any distinction in your code there.
    – Frank
    Jul 30, 2012 at 6:30
  • My point was to explain the option pattern like if you are using a custom api and want to pass nothing if value is empty.
    – FUD
    Jul 31, 2012 at 5:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.