Search code examples
scalaprotocol-buffers

How to unwrap Option[MyClassName]?


I am getting a Type mismatch with following error:

Type mismatch, expected: Color, actual Option[Color]

How can I unwrap it?

Below are more details

case class ColorDetail(
    color: Option[Color],
    shades: List[Shade]
)

....

colorToProtobuf(colorDetail.color)

....

def colorToProtobuf(c: Color): ColorMessage = {
  ...
}

Solution

  • .get:

    case class ColorDetail(
        color: Option[Color],
        shades: List[Shade]
    )
    val c = ColorDetail(Some(Color("Green")), List())
    c.color // Some(Color(Green))
    c.color.get // Color(Green)
    

    This will fail if color is None though. If you are okay with that, just let it fail. If you want to give it a default value (ie if a color is not provided), is .getOrElse(...):

    case class ColorDetail(
        color: Option[Color],
        shades: List[Shade]
    )
    val c = ColorDetail(None, List())
    c.color // None
    c.color.getOrElse(Color("Blue")) // Color(Blue)