Why Diffrence of annomous Impl of Interface declared in between Java and Kotlin


#1

inteface with only one method

  1. declared in Java, annomous impl can writtern in closure form, like fun call

  2. declared in Kotlin, annomous impl should use " object:".
    eg:

    public interface JMathJob {
    Integer plus(Integer left, Integer right);
    }
    interface KMathJob {
    fun plus(left: Int, right: Int): Int
    }
    val jjob = JMathJob { left, right -> left + right } // valid
    val kjob = KMathJob { left, right -> left + right } // invalid

why ?


#2

This is called SAM conversion and Kotlin only supports this for Java interfaces and not for Kotlin code. The documentation says:

Also note that this feature works only for Java interop; since Kotlin has proper function types, automatic conversion of functions into implementations of Kotlin interfaces is unnecessary and therefore unsupported.

If you want to dig deeper into this, here are a two past discussions of this topic:



#3

Java and Kotlin are 99% interoperable.

See https://youtrack.jetbrains.com/issue/KT-7770