我偶尔会遇到以下模式,我基本上有 a PartialFunction[SomeType,AnotherType]
,并希望将其视为 a 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
}
有没有办法以一种避免默认情况并将结果包装在定义位置的方式编写上述函数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)
}
有没有办法在不定义中间函数的情况下做到这一点?我已经按照以下方式尝试了各种方法,但还没有任何东西可以编译:
def f:Function[SomeType,Option[AnotherType]] = {
case s1:SubType1 => AnotherType(s1.whatever)
case s2:SubType2 => AnotherType(s2.whatever)
}.lift