scala.Some cannot be cast to java.lang.String
Asked Answered
A

4

7

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

Anecdotage answered 12/7, 2013 at 17:22 Comment(1)
Simple answer is use the foreach method.Missie
S
10

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
}
Supervene answered 12/7, 2013 at 17:31 Comment(2)
You'd probably use orNull instead of getOrElse(null).Helicopter
orNull doesn't always work. I just tried java.lang.Integer instead of java.lang.String and then compilation for orNull fails with Cannot prove that Null <:< Int.Karisakarissa
G
4

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

Gonfalonier answered 12/7, 2013 at 17:34 Comment(0)
M
3
x.map(_.toString).getOrElse("")
Manama answered 31/7, 2013 at 1:32 Comment(0)
W
1

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
}
Weeden answered 12/7, 2013 at 17:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.