Question

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!!

Was it helpful?

Solution

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
}

OTHER TIPS

Casting isn't how you should be looking at conversions when it comes to Options. Have a look at the following REPL session:

C:\>scala -deprecation -unchecked 
Welcome to Scala version 2.10.0 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0).
Type in expressions to have them evaluated. Type :help for more information.

scala> val email:Option[String] = Some("x@y.com") 
email: Option[String] = Some(x@y.com)

scala> email.getOrElse("defaults@example.com") 
res0: String = x@y.com

scala>

You might also want to look at this SO question: What is the point of the class Option[T]?

and the Options API here

Generally speaking, casting/coercion are kind-of taboo in FP world. :)

x.map(_.toString).getOrElse("")

You may want use pattern matching:

x.email match {
  case Some(email) => // do something with email
  case None => // did not get the email, deal with it
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top