[英]Generic Try[T] function
I want to refactor some common error handling logic in a generic Try[T]
handler, similar to this: 我想在通用的
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
}
}
}
Seems I can't match against the type T
because of type erasure. 由于类型擦除,我似乎无法与
T
类型匹配。 But I can't pass an Any
to successFunc
. 但是我不能将
Any
传递给successFunc
。
How can I implement this function? 如何实现此功能?
Mapping on a try applies a function to the value held by a success of that try, what you have there is not a Success
or a Failure
, it's a T
, what you want is a match
: 尝试映射将功能应用于该尝试的成功值,您所没有的是
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) =>
}
}
The usage in your case of map
would be: 您在
map
情况下的用法是:
t.map(someT => successFunc(someT))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.