5

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?

josmith42
  • 848
  • 2
  • 10
  • 18
  • I don't why but Java does not have error when exposing private class on public interface. But if the class is written in Kotlin, you cannot compile. – Joshua Sep 27 '17 at 07:39
  • This sounds like a bug in the kotlin compiler to me... you may want to open an issue at https://youtrack.jetbrains.com/issues/KT – Roland Sep 05 '18 at 07:37

0 Answers0