https://kotlinlang.org logo
#announcements
Title
# announcements
m

Mahendran

09/06/2019, 10:25 AM
Kotlin interface to lambda? (Any Trick)
c

Can Orhan

09/06/2019, 10:33 AM
Do you mean something like?:
Copy code
interface MyInterface {
    fun myFunction()
}

fun usesMyInterface(myInterface: MyInterface) { }

usesMyInterface(object : MyInterface {
    override fun myFunction() {
        
    }
})
s

Stephan Schroeder

09/06/2019, 10:52 AM
@Can Orhan not a lambda though
interestingly this compiles
Copy code
fun main() {
    usesMyInterface({name: String -> println("hello $name")} as MyInterface)
}

interface MyInterface {
    fun myFunction(s: String)
}

fun usesMyInterface(myInterface: MyInterface) {
    myInterface.myFunction("Yoda")
}
but throws an error. https://pl.kotl.in/_stgLor9V
c

Can Orhan

09/06/2019, 10:59 AM
Yeah sorry 😄 I had difficulty understanding exactly what the question wanted in the first place. I should have just said nothing 😄
s

SiebelsTim

09/06/2019, 11:00 AM
You want SAM conversions for kotlin interfaces. There is an open ticket for it.
c

Casey Brooks

09/06/2019, 2:12 PM
Rather than defining it as an interface, maybe try writing it as a typealias.
typealias MyInterface = (s: String)->Unit
2 Views