2014-04-21 66 views
2

我想將部分函數轉換爲「安全」部分函數,​​即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)) 
} 
+2

更好的什麼? –

+2

[PartialFunction's](http://www.scala-lang.org/api/current/index.html#scala.PartialFunction)'lift'方法如何。將'PartialFunction [A,B]'轉換爲'A => Option [B]' – Dylan

+0

'Option [T]'絕對是正確的方法。 –

回答

-1

您可以使用for表達式定義safe

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