Skip to content

Instantly share code, notes, and snippets.

@pbriggs28

pbriggs28/KotlinSAMIssue.kt Secret

Created Aug 31, 2020
Embed
What would you like to do?
// 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() }
}
@EndzeitBegins

This comment has been minimized.

Copy link

@EndzeitBegins EndzeitBegins commented Sep 3, 2020

Hello @pbriggs28,

as written under the SO blog post you need to declare the Kotlin SAM interface as fun interface FooKotlinInterface instead of interface FooKotlinInterface, see the official Kotlin docs for more information

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.