Skip to content

Evaluating function value can lead to ClassCastException, when function type has by-name parameter #18756

Closed
@heritamas

Description

@heritamas

Compiler version

3.3.0, 3.2.2, 3.2.1, 3.2.0

Minimized code

For reproduction, use Scala REPL, the issue seems to be REPL-related.

scala> val f: ( => Int) => Int = i => i ; f(1)
scala> f(1)

Output

scala> val f: ( => Int) => Int = i => i ; f(1)
val f: (=> Int) => Int = Lambda$1323/0x00007f9db44ac208@2dbf2da
val res0: Int = 1
                                                                                                                                                                     
scala> f(1)
java.lang.ClassCastException: class java.lang.Integer cannot be cast to class scala.Function0 (java.lang.Integer is in module java.base of loader 'bootstrap'; scala.Function0 is in unnamed module of loader java.net.URLClassLoader @4a951911)
  at scala.Function1.apply$mcII$sp(Function1.scala:69)
  ... 34 elided

Expectation

As f is basically the identity (for Ints), f(1) shall evaluate to 1.
Note: if the assignment and the evaluation entered on the same line, or entered in the same entry, such as:

scala> val f: ( => Int) => Int = i => i
     | f(1)
     | 
val f: (=> Int) => Int = Lambda$1324/0x00007f3d904a4208@7e38e254
val res0: Int = 1

the issue exhibits itself only when f is evaluated upon a different entry.

scala> f(2)
java.lang.ClassCastException: class java.lang.Integer cannot be cast to class scala.Function0 (java.lang.Integer is in module java.base of loader 'bootstrap'; scala.Function0 is in unnamed module of loader java.net.URLClassLoader @4a951911)
  at scala.Function1.apply$mcII$sp(Function1.scala:69)
  ... 34 elided

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions