Consider the following Java class:
package javapkg;
public class JavaClass {
private interface JavaInterface {
void foo();
}
public void bar(JavaInterface ji) {
ji.foo();
}
}
Kotlin code that uses this class's inner interface with a SAM conversion (note that KotlinClass
is in a different package):
package kotlinpkg
import javapkg.JavaClass
class KotlinClass {
fun f() {
val jc = JavaClass()
// Does not compile:
// "Cannot access 'JavaInterface': it is private in 'JavaClass'"
jc.bar(object : JavaClass.JavaInterface{
override fun foo() { }
})
// Compiles and runs fine on Android Nougat, but throws
// a NoClassDefFoundError exception on Kitkat
jc.bar { }
}
}
Now, if you make the inner JavaInterface
public, the Kotlin code (both the SAM conversion and the object expression) compiles and runs correctly on all platforms. The object expression fails to compile with the interface being private because JavaClass
and KotlinClass
are in separate packages, and I'm guessing the SAM conversion fails with a runtime exception for the same reason.
My question: why does the SAM conversion successfully compile? It seems like it ought not to because the interface is private, and worse it causes a runtime exception in Kitkat. Also, the object expression does NOT compile. Is this a bug in the Kotlin compiler, or is this deliberate?