本文介绍了在通用方法中避免投射到无的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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'没有被推断或明确设置为真实类型?

Is there a way to write #foo so that it returns an Any if 'U' is not inferred or set explicitly to a "real" type?

推荐答案

没有。静态类型是 U 。如果这被推断为 Nothing ,编译器将不允许类型为任何的返回值。

No. The static type is U. If this is inferred as Nothing, the compiler won't allow a return value of type Any.

您可以改善运行时错误信息:

You can improve the runtime error message:

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

或者按照Arjan的建议。

Or follow the Arjan's suggestion.

这篇关于在通用方法中避免投射到无的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:10