This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Accoriding Kotlin 1.4.0 release blog, we should be able to define SAM interfaces in Kotlin and use them the | |
// same way we can use them if they are defined in Java but the code below still does not compile | |
// https://stackoverflow.blog/2020/08/26/kotlin-1-4-released-to-improve-performance/ | |
// As typealias (works) | |
typealias FooTypeAlias = () -> Boolean | |
fun runAsTypeAlias(func: FooTypeAlias): Boolean { | |
return func.invoke() | |
} | |
// As Java SAM interface (works) | |
// Defined in FooJavaInterface.java: public interface FooJavaInterface { boolean samJavaInterfaceCall();} | |
fun runAsJavaInterface(func: FooJavaInterface): Boolean { | |
return func.samJavaInterfaceCall() | |
} | |
// As Kotlin SAM interface (doesn't work) | |
interface FooKotlinInterface { | |
fun samKotlinInterfaceCall(): Boolean | |
} | |
fun runAsKotlinInterface(func: FooKotlinInterface): Boolean { | |
return func.samKotlinInterfaceCall() | |
} | |
// Function that *should* work for typealias, Java SAM interface, and Kotlin SAM interface calls | |
fun doSomething(): Boolean { | |
return true | |
} | |
fun main() { | |
// prints 1.4.0 | |
println(KotlinVersion.CURRENT) | |
// compiles | |
runAsTypeAlias { doSomething() } | |
// compiles | |
runAsJavaInterface { doSomething() } | |
// Should compile in kotlin 1.4.0 but doesn't: | |
// Type mismatch. | |
// Required: | |
// FooKotlinInterface | |
// Found: | |
// () → Boolean | |
runAsKotlinInterface { doSomething() } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello @pbriggs28,
as written under the SO blog post you need to declare the Kotlin SAM interface as
fun interface FooKotlinInterface
instead ofinterface FooKotlinInterface
, see the official Kotlin docs for more information