Scala. Some cannot be added to java.lang.String

In this application, I get this error:

scala.Some cannot be cast to java.lang.String 

When trying this:

 x.email.asInstanceOf[String] 

x.email is the [String] option

Edit: I understand that I am dealing with different types here, I'm just wondering if there was a more concise way of doing nothing with None, and then

 match { case....} 

sequence. Since I pass x.email to String for JSON purposes, the null field will be handled by the JSON object, and I should not have to deal with it explicitly. Sorry for the ambiguity !!

+7
casting scala scalatra
source share
4 answers

Well, this is clear from the errors and types that x.email are not String ...

First decide how you want to handle None (a valid option for something like Option[String] ). Then you 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 } 

Alternatively, check out the get and getOrElse on the class Option .

If you want to "degrade" a parameter in String with a possible null value, use

 x.email.orNull // calls getOrElse(null) 

Finally, if you just don't care about the None case (and want to ignore it), just use a simple โ€œto understandโ€ that will โ€œskipโ€ the body in the None case:

 for (value <- x.email) { // value is of type String } 
+9
source share

Casting is not how you should look at conversions when it comes to options. See 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 can also look at this SO question: What is the meaning of the Option [T] class?

and the API here

Generally speaking, casting / coercion is a kind of taboo in the FP world. :)

+4
source share

You may need to use pattern matching:

 x.email match { case Some(email) => // do something with email case None => // did not get the email, deal with it } 
+1
source share
 x.map(_.toString).getOrElse("") 
+1
source share

All Articles