https://kotlinlang.org logo
Title
k

karelpeeters

10/31/2017, 10:06 PM
Is there no way to construct an anonymous instance of a SAM-ish abstract class from a lambda? For example:
//java code
public abstract class Test {
    public abstract void run()
}

//kotlin code
fun testFoo(test: Test) = test.run()

fun main(args: Array<String>) {
    testFoo(object : Test() {
        override fun run() {
            println("hey")
        }
    })
}
It just feels unnecessary, are there plans to do something about this?
e

emmax

10/31/2017, 10:27 PM
The preferred way to do that with kotlin is to define that
testFoo
takes a function to begin with instead of the abstract Test class I don't see this being supported. https://kotlinlang.org/docs/reference/java-interop.html#sam-conversions Note towards the bottom
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.
k

karelpeeters

10/31/2017, 10:28 PM
Yup, unfortunately this is for a Java interop case.
e

emmax

10/31/2017, 10:31 PM
oh gotcha, didn't see Test is a java class 🙂 nvm
k

karelpeeters

10/31/2017, 10:31 PM
I should have specified that, there's no syntax difference in this case.
e

emmax

10/31/2017, 10:32 PM
Well actually, it is defined as a Kotlin class in your example.
abstract fun run()
ah, better 🙂
k

karelpeeters

10/31/2017, 10:33 PM
It's been I while since I wrote any Java 🙂, thanks.
public void
feels so ugly now.
🙂 1
b

bj0

10/31/2017, 10:50 PM
You could just pass the lambda into
testFoo
and create the object in there:
inline fun runnable(crossinline init: Runnable.() -> Unit) = object : Runnable {
    override fun run() = this.init()
}