Reputation: 1047
Say, there is a case class
case class MyCaseClass(a: Int, b: String)
and an Option[MyCaseClass]
variable
val myOption: Option[MyCaseClass] = someFunctionReturnOption()
Now, I want to map this Option variable like this:
myOption map {
case MyCaseClass(a, b) => do some thing
}
It seems the compiler reports error like It needs Option[MyCaseClass], BUT I gave her MyCaseClass, bla bla..
. How to use pattern match in Optional case class ?
Upvotes: 0
Views: 884
Reputation: 20435
Consider extracting the Option
value like this,
myOption map {
case Some(MyCaseClass(a, b)) => do some thing
case None => do something else
}
or else use collect
for a partial function, like this
myOption collect {
case Some(MyCaseClass(a, b)) => do some thing
}
Update
Please note that as commented, the OP code is correct, this answer addresses strictly the last question How to use pattern match in Optional case class ?
Upvotes: 2
Reputation: 4999
MyOption match {
Some(class) => // do something
None => // do something.
}
Or
MyOption map (class =>//do something)
Upvotes: 0