加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

泛型 – 在通用方法中避免强制转换为Nothing

发布时间:2020-12-16 18:21:35 所属栏目:安全 来源:网络整理
导读:scala def foo[U](t: Any) = t.asInstanceOf[U]foo: [U](t: Any)Uscala val s: String = foo("hi")scala val n = foo("hi")java.lang.ClassCastException: java.lang.String cannot be cast to scala.runtime.Nothing$ at .init(console:6) at .clinit(conso
scala> def foo[U](t: Any) = t.asInstanceOf[U]
foo: [U](t: Any)U

scala> val s: String = foo("hi")

scala> val n = foo("hi")
java.lang.ClassCastException: java.lang.String cannot be cast to scala.runtime.Nothing$
    at .<init>(<console>:6)
    at .<clinit>(<console>)
    at RequestResult$.<init>(<console>:9)
    at RequestResult$.<clinit>(<console>)
    at RequestResult$scala_repl_result(<console>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at scala.tools.nsc.Interpreter$Request$$anonfun$loadAndRun$1$$anonfun$apply$18.apply(Interpreter.scala:981)
    at scala.tools.nsc.Interpreter$Request$$anonfun$loadAndRun$1$$anonfun$apply$18.apply(Interpreter.scala:981)
    at scala.util.control.Exce...

有没有办法编写#foo,以便它返回一个Any,如果’U’没有被推断或明确设置为“真实”类型?

解决方法

不可以.静态类型是U.如果将其推断为Nothing,则编译器将不允许返回Any类型的值.

您可以改进运行时错误消息:

def foo[U: Manifest](t: Any): U = if (implicitly[Manifest[U]] == manifest[Nothing]) 
  error("type not provided") 
else t.asInstanceOf[U]

或者按照Arjan的建议.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读