gpt4 book ai didi

scala 早期初始化程序与 var 导致 ClassCastException

转载 作者:行者123 更新时间:2023-12-03 03:46:17 24 4
gpt4 key购买 nike

我尝试了以下代码:

class C(val g: Int => Int)
object C {
object A extends {
var f: Int => Int = x => x
} with C(x => f(x) + 1)

def main(args: Array[String]): Unit = {
println(A.g(3))
}
}

它可以编译(scala版本2.12.2),但在运行时抛出异常:

Exception in thread "main" java.lang.ExceptionInInitializerError
at pkg1.C$.main(C.scala:14)
at pkg1.C.main(C.scala)
Caused by: java.lang.ClassCastException: scala.runtime.ObjectRef cannot be cast to scala.Function1
at pkg1.C$A$.<init>(C.scala:10)
at pkg1.C$A$.<clinit>(C.scala)
... 2 more

为什么会发生这种情况?

最佳答案

这可能是由于使用从 2.12 开始的函数的方法句柄而导致的 scalac 错误(/变量早期初始化和 lambda 类型引用的类类型的功能的意外干扰)。 :

Scala and Java 8 interop is also improved for functional code, as methods that take functions can easily be called in both directions using lambda syntax. The FunctionN classes in Scala’s standard library are now Single Abstract Method (SAM) types, and all SAM types are treated uniformly – from type checking through code generation. No class file is generated for a lambda; invokedynamic is used instead.

编辑:除了将 var 更改为 val 之外,我找不到解决此问题的良好解决方法,但我想这在您的用例中是不可能的。

关于scala 早期初始化程序与 var 导致 ClassCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44447887/

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