[英]Mapping with a function that returns Try[T] to return a Try[T] instead a List[Try[T]]
[英]Generic Try[T] function
我想在通用的Try[T]
處理程序中重構一些常見的錯誤處理邏輯,如下所示:
def handler[T](t: Try[T], successFunc: T => Unit) = {
t.map {
case Success(res) => { // type mismatch required T, found Any (in successFunc line)
//case Success(res: T) => { // Type abstract type pattern T is unchecked since it is eliminated by erasure
successFunc(res)
}
case Failure(e: CustomException) => {
// custom actions
}
case Failure(e) => {
// custom actions
}
}
}
由於類型擦除,我似乎無法與T
類型匹配。 但是我不能將Any
傳遞給successFunc
。
如何實現此功能?
嘗試映射將功能應用於該嘗試的成功值,您所沒有的是Success
或Failure
,它是T
,您想要的是一個match
:
def handler[T](t: Try[T], successFunc: T => Unit) = {
t match {
case Success(res) =>
successFunc(res)
case Failure(e: FileNotFoundException) =>
case Failure(e) =>
}
}
您在map
情況下的用法是:
t.map(someT => successFunc(someT))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.