gpt4 book ai didi

generics - 避免在泛型方法中强制转换为Nothing

转载 作者:行者123 更新时间:2023-12-04 22:25:30 25 4
gpt4 key购买 nike

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,以便在不推断'U'或将其显式设置为“真实”类型的情况下返回Any?

最佳答案

否。静态类型为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的建议。

关于generics - 避免在泛型方法中强制转换为Nothing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3157422/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com