从选项中收集
使用get 方法(参见下面给出的实现)将给定值包装在选项周围,然后收集所需的值。
使用选项包装值,然后收集您想要收集的任何内容。
Option(x: Any).collect { case 1 => 1 }
或
x get { case 2 => 2 } // get implementation is given below
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
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 }
返回无。
现在,如果您想要类型安全,请进行以下更改
类型安全
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