Scala:抽象类型模式A被取消选中,因为它被擦除消除
发布时间:2020-12-16 21:32:49 所属栏目:安全 来源:网络整理
导读:我正在编写只能捕获特定类型的异常的函数. def myFunc[A : Exception]() { try { println("Hello world") // or something else } catch { case a: A = // warning: abstract type pattern A is unchecked since it is eliminated by erasure }} 在这种情况
我正在编写只能捕获特定类型的异常的函数.
def myFunc[A <: Exception]() { try { println("Hello world") // or something else } catch { case a: A => // warning: abstract type pattern A is unchecked since it is eliminated by erasure } } 在这种情况下,绕过jvm类型擦除的方法是什么? 解决方法
你可以像
this answer那样使用ClassTag.
但我更喜欢这种方法: def myFunc(recover: PartialFunction[Throwable,Unit]): Unit = { try { println("Hello world") // or something else } catch { recover } } 用法: myFunc{ case _: MyException => } 使用ClassTag: import scala.reflect.{ClassTag,classTag} def myFunc[A <: Exception: ClassTag](): Unit = { try { println("Hello world") // or something else } catch { case a if classTag[A].runtimeClass.isInstance(a) => } } 还要注意,一般来说,您应该使用Try with recover方法:尝试只捕获 def myFunc(recover: PartialFunction[Throwable,Unit]) = { Try { println("Hello world") // or something else } recover { recover }.get // you could drop .get here to return `Try[Unit]` } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |