我想在通用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
。
如何实现此功能?
答案 0 :(得分:8)
尝试映射会将函数应用于该尝试成功所持有的值,您所拥有的值不是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))