Hey there, I'm updating an project from Kotlin 1.9...
# getting-started
k
Hey there, I'm updating an project from Kotlin 1.9.20 to 2.1.0 and running into some weirdness with the K2 compiler, I have a fun interface with a generic type and a suspending function. When calling a function that receives this functional interface and creates an object out of it I get a casting exception:
Copy code
Exception in thread "main" java.lang.ClassCastException: class main$1 cannot be cast to class kotlin.jvm.functions.Function1 (main$1 and kotlin.jvm.functions.Function1 are in unnamed module of loader 'app')
Here are some past youtrack issues that are marked as fixed which seem fairly similar to this problem: https://youtrack.jetbrains.com/issue/KT-67933/K2-no-conversion-between-fun-interfaces-if-target-has-suspend https://youtrack.jetbrains.com/issue/KT-68849/K2-ClassCastException-cannot-be-cast-to-ko[…]tion2-caused-by-passing-lambda-to-SAM-constructor-results Here's a small code example that triggers the exception:
Copy code
fun interface Foo<P : Number> : suspend (P) -> Unit

class Bar<P : Number>(
    foo: Foo<P>
) : Foo<P> by foo

fun <P : Number> create(foo: Foo<P>): Bar<P> = Bar(foo)

fun main() {
    create<Int> {}
}
Does anyone know what could be causing this? I know that changing create to
Bar(foo::invoke)
resolves the issue but this pattern is quite common in the project and the error only occurs at runtime. The issue does not occur when the P: Number generic is removed or when the functional interface is not suspending, so it seems related to that in specific.
d
Please file a new issue