Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 337
Alex Spangher Avatar asked Jul 12 '13 17:07

Alex Spangher


4 Answers

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
}
like image 114
Richard Sitze Avatar answered Nov 04 '22 08:11

Richard Sitze


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("[email protected]") 
email: Option[String] = Some([email protected])

scala> email.getOrElse("[email protected]") 
res0: String = [email protected]

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. :)

like image 22
S.R.I Avatar answered Nov 04 '22 10:11

S.R.I


x.map(_.toString).getOrElse("")
like image 3
mirandes Avatar answered Nov 04 '22 10:11

mirandes


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
}
like image 1
Jiri Kremser Avatar answered Nov 04 '22 09:11

Jiri Kremser