Search code examples
scalapattern-matchingsprayfor-comprehension

Concisely mapping an Optional of one type to another if it exists?


So I've got a bunch of case classes that take on this format:

case class A(value: String)
case class B(value: String)
case class C(value: String)

I'm taking in several Option[String] values as parameters in a function and I want to create Option[A], Option[B] if the values from the parameters isn't None.

I'm currently doing it like this:

val first = parameterOptional match {
    case Some(theStringValue) => Some(A))
    case None => None
}

And it works but I wanted to know if there's a more consise way of doing this, I'm very new to Scala.

Variable names in the examples have obviously been altered.

Thanks


Solution

  • as I understand you want to wrap optional parameter into one of the case classes? Then you can simply use map:

    scala> case class C(value: String)
    defined class C
    
    scala> val optionalParam: Option[String] = Some("zzz")
    optionalParam: Option[String] = Some(zzz)
    
    scala> optionalParam.map(C)
    res0: Option[C] = Some(C(zzz))
    
    scala> val optionalParam: Option[String] = None
    optionalParam: Option[String] = None
    
    scala> optionalParam.map(C)
    res1: Option[C] = None