2014-09-22 21 views
0

我有以下的現有方法:扔Throwable的fromTryCatch - 和調整方法的類型正確

def test: \/[Throwable, Person] = { 
    \/.fromTryCatch { 
    //existing logic has potential to throw exception (from calls like .toInt) etc 
    //now via following for comprehension want to combine Throwable with return type \/[Throwable,Person] 
    for { 
     p <- q.firstOption.\/>(new Throwable("can't find record for person with id = " + id)) 
    } yield p 
    } 
} 

將會產生以下錯誤:

type mismatch; found : scalaz.\/[Throwable,Person] (which expands to) scalaz.\/[Throwable,Person] required:Person 

我怎麼排列的返回值類型理解類型爲def test

回答

0

fromTryCatch預計值爲Person,可能會引發異常。

因此,您不需要在\/中包裝異常,只需在fromTryCatch塊中引發異常,它將自動捕獲幷包裝。

或者,您可以簡單地刪除fromTryCatch,因爲您已經在例如\/[Throwable, Person](例如,

def test : \/[Throwable,Person] = 
    for { 
    p <- q.firstOption.\/>(new Throwable(s"can't find record for person with id = $id)) 
    } yield p 

如果您不是需要兩者混合使用,你可以這樣做

def test : \/[Throwable,Person] = \/.fromTryCatch { 
    mayThrow() 

    val res = for { 
    p <- q.firstOption.\/>(new Throwable("can't find record for person with id ="+id)) 
    } yield p 

    res match { 
    case \/-(p) => p 
    case -\/(e) => throw e 
    } 
} 

或更好的,你可以單獨的範圍和使用fromTryCatch只在必要時,像

def test : \/[Throwable,Person] = 
    for { 
    _ <- \/.fromTryCatch { mayThrow() } 
    p <- q.firstOption.\/>(new Throwable("can't find record for person with id ="+id)) 
    } yield p 
+0

正如原文所述'for'comprehension並不是我在'\ /。fromTryCatch'中唯一的事情,是我現在添加的一個新塊。 '\ /。fromTryCatch'中的現有邏輯具有可以拋出異常的其他代碼(一個例子是它調用了'.toInt')(這只是一個例子,但是在原始'\ /。fromTryCatch中還有其他潛在的代碼塊''有可能拋出異常,所以它不僅僅限於'for'的理解 – 2014-09-22 16:27:30

+0

@VikasPandya,請參閱我的編輯 – 2014-09-22 16:45:39

+0

你可能包含你正在使用的導入嗎?我正在學習scalaz並且跑過這個''''' 「這是從哪裏來的(不能真的是google的),謝謝。 – Jaap 2015-02-18 21:51:55