In this application, I'm getting this error:
scala.Some cannot be cast to java.lang.String
When trying this:
x.email.asInstanceOf[String]
x.email is an Option[String]
Edit: I understand that I'm dealing with different types here, I was just wondering if there were a more concise way to do nothing with None then a
match { case....}
sequence. Because I am casting x.email into a String for JSON purposes, a null field will be handled by the JSON object, and I don't explicitly have to deal with it. Sorry for being unclear!!
Well, it's clear to you from the errors and types that x.email
is not a String
...
First, decide how you want to handle None
(a valid option for something of type Option[String]
). You then have a number of options, including but not limited to:
x.email match {
case None => ...
case Some(value) => println(value) // value is of type String
}
Alternately, take a look at the get
and getOrElse
methods on class Option
.
If you want to "degrade" the option to a String with a possible null
value, then use
x.email.orNull // calls getOrElse(null)
Finally, if you just don't care about the None
case (and want to ignore it), then just use a simple "for comprehension" which will "skip" the body in the None
case:
for (value <- x.email) {
// value is of type String
}