Reputation: 35988
I have a case class like this:
case class ColorDetail(
color: Option[Color],
shades: List[Shade]
)
I have a method with this signature:
def colorFromProtoBuf(msg: ColorMessage): Color = {
...
}
When I try to do:
ColorDetail(
color = colorFromtProtoBuf(...), //Type mismatch here
shades = ...
)
I get a
Type mismatch, expected: Option[Color], actual: Color
How can I resolve this without changing my case class or method signature. Ideally I would like to just change the line where I'm getting an error. Is there a way I can convert it to Option[Color]
instead of just Color
Upvotes: 0
Views: 292
Reputation: 27421
If colorFromProtoBuf
is guaranteed to succeed you can simply wrap it in Some
:
color = Some(colorFromProtoBuf(...))
If colorFromProtoBuf
might return null
then use Option
which will convert null
values to None
:
color = Option(colorFromProtoBuf(...))
If there is a chance that colorFromProtoBuf
might throw an error then use Try
:
color = Try(colorFromProtoBuf(...)).toOption
Finally, if colorFromProtoBuf
might fail and you can edit this function, change the signature to return Option[Color]
and return None
on failure or Some(color)
on success.
def colorFromProtoBuf(msg: ColorMessage): Option[Color] = {
(I know this is not a one-line answer, but it might be the correct answer!)
Upvotes: 3
Reputation: 1868
color = Option(colorFromtProtoBuf(...))
color
will be assigned to Some(Color)
or None
if your function returns null
Upvotes: 4