2

Say I have this Java and Kotlin interfaces:

public interface JavaInterface {

    void onTest();
}

interface KotlinInterface {

    fun onTest()
}

Why can't I create an instance of Kotlin interface without constructor?

// this is okay
val javaInterface: JavaInterface = JavaInterface {

}

// compile-time exception: interface does not have constructor
val kotlinInterface1: KotlinInterface = KotlinInterface {

}

// this is okay
val kotlinInterface2: KotlinInterface = object : KotlinInterface {
    override fun onTest() {

    }
}

Why can't I create an instance of KotlinInterface the way I did with JavaExample just like the first example?

Hendra Anggrian
  • 5,780
  • 13
  • 57
  • 97

1 Answers1

1

That's because Kotlin has SAM ("single abstract method") only for Java interfaces. It's this way by design. There is some info on this on the docs as well:

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.

Related issue

Mibac
  • 8,990
  • 5
  • 33
  • 57
  • I accept the fact that it is not supported. But I can't understand why such feature is unnecessary in Kotlin? It is such a convenient way to create an instance of SAM interfaces. – Hendra Anggrian Jul 10 '17 at 00:15
  • @HendraAnggrian Andrey Breslav (kotlin project lead) said: SAM-conversions only work for Java methods, not supported for Kotlin functions, because Kotlin has nice functional types, and there's no need for SAM conversion – Mibac Jul 10 '17 at 00:17
  • Have a look at this link for some more info https://discuss.kotlinlang.org/t/kotlin-and-sam-interface-with-two-parameters/293/2 – Mibac Jul 10 '17 at 00:20
  • I think I might have know why now. Interfaces are easily replaced with Unit in Kotlin. Thanks for helpful links! – Hendra Anggrian Jul 10 '17 at 00:40