Scala:抽象类型模式A未被选中,因为通过擦除将其消除 [英] Scala: abstract type pattern A is unchecked since it is eliminated by erasure

查看:53
本文介绍了Scala:抽象类型模式A未被选中,因为通过擦除将其消除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写仅可捕获特定类型异常的函数.

I am writing the function that can catch exceptions of the certain type only.

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类型擦除的正确方法是什么?

What is the corrent way to bypass jvm type erasure in such case?

推荐答案

您可以像中那样使用 ClassTag 这个答案.

You could use ClassTag like in this answer.

但是我更喜欢这种方法:

But I'd prefer this approach:

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 recover 方法一起使用: Try 将仅捕获

Note also that in general you should use Try with recover method: Try will catch only NonFatal exceptions.

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]`
}

这篇关于Scala:抽象类型模式A未被选中,因为通过擦除将其消除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆