简体   繁体   中英

How to map an Option case class

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 ?

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 ?

MyOption match {

   Some(class) => // do something
   None => // do something. 

 }

Or

MyOption map (class =>//do something) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM