I'd like to pass in a function around as a listener, but I don't want to have to manually manage this function's signature in a multiple number of places. If I could typedef a function signature this would help out. In Java world I use an interface with a single function, a single abstract method, for this. I could pass instances of that interface around. I could do this with Kotlin too except in Java I can use an anonymous function in a function argument, like you can with a Runnable, but not for interfaces defined with Kotlin.
Someone suggested on IRC to use companion objects and functions in classes to achieve this, but that’s pretty verbose and even much less readable. This is a pretty big reason for me to not want to use Kotlin, but maybe I’m just doing this wrong?
To explain with code:
public interface Bar {
fun runBar(stuff: Stuff): List<Result>
}
Then in my code somewhere it would be nice to just be like:
class Foo () {
runBar(bar: Bar) {
val results = bar.runBar(stuff)
}
}
And then somewhere else:
def foobar() {
runBar((stuff) -> {
val r = ArrayList<Result>()
... //do stuff
return r
})
}
^^ this doesn’t seem possible, and that’s really, very much unfortunate.
Like not having a really easy way to pass functions around as arguments to other functions or as variables is a very undesirable thing. SAM’s make this trivial in Java 8, and in Kotlin it seems like you have to jump through hoops to do this. You either manage your function signatures manually all over the place or you create verbose classes or objects wherever you want to pass a function around.
EDIT
Someone indicated you could accomplish what I want this way:
interface Foo {
fun runFoo(bar: Bar) : BarData
}
class Bar {
public val bar: String = “bar”
}
class BarData {
public val barData: Int = 1;
}
fun main(args: Array<String>) {
test(object: Foo {
override fun runFoo(bar: Bar) : BarData {
return BarData()
}
})
}
fun test(foo: Foo) {
val barData: BarData = foo.runFoo(Bar())
}
Which works, but it’s much more verbose than Java 8’s way. The call to test
would be one line in Java 8, not 5.