本文介绍了是否有更好的方法来提升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 _ =>无
}

有没有办法以避免默认情况下,并将结果包装在 Some 中它的定义位置?到目前为止我所得到的最好的是这样的:
$ b $ pre $ 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 :函数[SomeType,Option [AnotherType]] = {
case s1:SubType1 => AnotherType(s1.whatever)
case s2:SubType2 => AnotherType(s2.whatever)
} .lift


解决方案

condOpt 在对象scala.PartialFunction中。从scaladoc:

pre $ def onlyInt(v:Any):Option [Int] = condOpt(v){case x:Int => x}


I occasionally come across the following pattern, where I essentially have a PartialFunction[SomeType,AnotherType], and want to treat it as a Function[SomeType,Option[AnotherType], eg:

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

Is there a way to write the above function in a way that avoids the default case and wrapping the result in Some where it's defined? The best I've come up with so far is this:

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)
}

Is there a way to do it without defining an intermediate function? I've already tried various things along the lines of the following, but haven't got anything to compile yet:

def f:Function[SomeType,Option[AnotherType]] = {
  case s1:SubType1 => AnotherType(s1.whatever)
  case s2:SubType2 => AnotherType(s2.whatever)
}.lift
解决方案

condOpt in object scala.PartialFunction. From the scaladoc:

def onlyInt(v: Any): Option[Int] = condOpt(v) { case x: Int => x }

这篇关于是否有更好的方法来提升Scala中的PartialFunction?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 00:24