我偶尔会遇到以下模式,本质上我有一个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
}
有没有一种方法可以避免默认情况并在定义时不用
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