微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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的建议.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐