Home > front end >  Can we convert option[string] to caseclass in scala?
Can we convert option[string] to caseclass in scala?

Time:01-13

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] => error it is showing but I want result

CodePudding user response:

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"))

CodePudding user response:

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)
  •  Tags:  
  • Related