有没有更好的方法在Scala中提升PartialFunction?

Kri*_*ala 3 functional-programming scala partialfunction

我偶尔会遇到以下模式,我基本上有一个PartialFunction[SomeType,AnotherType],并希望将其视为一个Function[SomeType,Option[AnotherType],例如:

def f(s:SomeType):Option[AnotherType] = s match {
  case s1:SubType1 => Some(AnotherType(s1.whatever))
  case s2:SubType2 => Some(AnotherType(s2.whatever))
  case _ => None
}
Run Code Online (Sandbox Code Playgroud)

有没有办法以避免默认情况并将结果包装在Some定义位置的方式编写上述函数?到目前为止我提出的最好的是:

def f(s:SomeType):Option[AnotherType] = pf.lift(s)
def pf:PartialFunction[SomeType,AnotherType] = {
  case s1:SubType1 => AnotherType(s1.whatever)
  case s2:SubType2 => AnotherType(s2.whatever)
}
Run Code Online (Sandbox Code Playgroud)

有没有办法在没有定义中间函数的情况下做到这一点?我已经尝试了以下几行,但还没有任何东西可以编译:

def f:Function[SomeType,Option[AnotherType]] = {
  case s1:SubType1 => AnotherType(s1.whatever)
  case s2:SubType2 => AnotherType(s2.whatever)
}.lift
Run Code Online (Sandbox Code Playgroud)

huy*_*hjl 6

condOpt在对象scala.PartialFunction中.来自scaladoc:

def onlyInt(v: Any): Option[Int] = condOpt(v) { case x: Int => x }
Run Code Online (Sandbox Code Playgroud)