我想在通用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
.
我该如何实现这个功能?
尝试映射将函数应用于该尝试成功所持有的值,您所拥有的值不是a Success
或a Failure
,它是a 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))