-2

When I tried to convert Some(string) into a case class I am getting an exception.

Ex:

val a:option[string]= Some("abc")
case class hello(a:string)
a.get.convertto[hello] => it is showing error
Hola Hola
  • 9
  • 2

2 Answers2

3

You need to allow for the Option being empty so avoid get and use getOrElse. Then just use the String to make the case class, like this:

val a: Option[String] = Some("abc")
case class hello(a: String)

val cc: hello = hello(a.getOrElse("default"))
Tim
  • 26,753
  • 2
  • 16
  • 29
3

The convertto you're looking for is map().

case class Hello(a: String)

val a: Option[String] = ??? //might be Some(s), might be None
val result: Option[Hello] = a.map(Hello)
jwvh
  • 50,871
  • 7
  • 38
  • 64