Scala early initializer with var throws ClassCastException

I tried the following code:

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))
    }
}

      

It can compile (in scala version 2.12.2) but throws an exception at runtime:

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

      

Why is this happening?

+3


source to share


1 answer


This is probably a rolling error (/ unintentional interference between early variable initialization functions and lambda reference class type) caused by using method descriptors for functions since 2.12 :

Scala and Java 8 interop are also improved for functional code, as methods that accept functions can easily be called in both directions using lambda syntax. The classes FunctionN

in Scala's standard library s are now single abstract method (SAM) types , and all SAM types are handled uniformly - from type checking to code generation. No class file is generated for the lambda file; Is used instead invokedynamic

.



Edit: I couldn't find a suitable way to solve this problem other than changing var

before val

, but I guess this is not possible in your use case.

+1


source







All Articles