安全的部分功能

时间:2014-04-21 10:26:45

标签: scala

我想将部分函数转换为“安全”部分函数,​​即PartialFunction[T,R]转换为PartialFunction[T,Try[R]],有没有比以下实现更好的方法?

def safe[T,R](pf:PartialFunction[T,R]):PartialFunction[T,Try[R]]=new PartialFunction[T, Try[R]]{
  def isDefinedAt(t:T) = pf.isDefinedAt(t)
  def apply(t:T) = Try(pf.apply(t))
}

1 个答案:

答案 0 :(得分:-1)

您可以使用safe表达式定义for

def safe[T,R](pf:PartialFunction[T,R]) = PartialFunction {
  (t:T) => for(a <- Try(pf(t))) yield a
}

或者使用隐式类:

object SafeImplicit {
  implicit class Safe[T,R](pf: PartialFunction[T,R]){
    def safe(t: =>T) = for(a<-Try(pf(t))) yield a
  }
}

import SafeImplicit.Safe
def f: PartialFunction[Int, String] = {case 1 => "one"}
def g: PartialFunction[Int, String] = {case 1 => "a".toInt;"one"}

f.safe(1)          // Success(one)
f.safe(2)          // Failure(scala.MatchError: 2 ...)
f.safe("a".toInt)  // Failure(java.lang.NumberFormatException ...)
g.safe(1)          // Failure(java.lang.NumberFormatException ...)