泛型 – 在通用方法中避免强制转换为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的建议. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 希尔排序(Shell sort)
- “-bash: /usr/local/bin/npm: No such file or directory”
- 【V8.Internal】Building V8 from bootstrap
- angularjs – 如何更改ng-tags-input separator? (默认:破
- angular – 移动目标元素时不会触发Click处理程序
- wercker.com连接到MySQL数据库
- 常用WebService一览表
- 结构-行为-样式-Angularjs-ngSanitize
- 相当于R控制台内的unix“less”命令
- 相同的cmd在shell中工作,但不在subprocess.Popen()中,用于D