Collect from option
get (. ), .
, , .
Option(x: Any).collect { case 1 => 1 }
x get { case 2 => 2 }
Scala REPL
scala> Option(1).collect { case 1 => 1 }
res0: Option[Int] = Some(1)
scala> Option(2).collect { case str: String => "bad" }
<console>:12: error: scrutinee is incompatible with pattern type;
found : String
required: Int
Option(2).collect { case str: String => "bad" }
^
scala> Option(2: Any).collect { case str: String => "bad" }
res2: Option[String] = None
scala> Option(2: Any).collect { case 2 => "bad" }
res3: Option[String] = Some(bad)
API- Nicer
implicit class InnerValue[A](value: A) {
def get[B](pf: PartialFunction[Any, B]): Option[B] = Option(value) collect pf
}
Scala REPL
scala> implicit class InnerValue[A](value: A) {
| def get[B](pf: PartialFunction[Any, B]): Option[B] = Option(value) collect pf
| }
defined class InnerValue
scala> 2.get { case 2 => 2}
res5: Option[Int] = Some(2)
scala> 2.get { case 3 => 2}
res6: Option[Int] = None
invoke . , Some None.
, API ( get) ,
2.get { case str: String => str }
None.
, ,
implicit class InnerValue[A](value: A) {
def get[B](pf: PartialFunction[A, B]): Option[B] = Option(value) collect pf
}
, A Any.
,
2.get { case str: String => str }
.
scala> 2.get { case str: String => str }
<console>:15: error: scrutinee is incompatible with pattern type;
found : String
required: Int
2.get { case str: String => str }
,
scala> (2: Any) get { case str: String => str}
res16: Option[String] = None