https://kotlinlang.org logo
Title
t

tipsy

01/20/2018, 11:16 AM
i have a pretty long questions about the different ways of calling a java method from kotlin, so i'm going to nest it into a thread
say i have a dummy method:
myMethod(Handler handler) { // Handler is a void->void @FunctionalInterface
    ...
}
in java, i can create non-anonymous handlers in three different ways:
MyClass {
    Handler fieldHandler = () -> {};
    methodRefHandler(Handler handler) {}
    ClassHandler implements Handler {}
}
and call myMethod like this:
myMethod(MyClass.fieldHandler);
myMethod(MyClass::methodRefHandler);
myMethod(new ClassHandler());
what i'm wondering is, what are all the possible ways of calling myMethod (the java version), from kotlin
k

kingsley

01/20/2018, 11:32 AM
Well. You could do the exact same things in Kotlin. By the way, for the sake of completeness, you missed anonymous instance of Handler, and using a lambda directly, which also works in both languages 🙂
t

tipsy

01/20/2018, 11:39 AM
i forgot to specify i'm only looking for non-anonymous instances (fixed now)
k

kingsley

01/20/2018, 11:41 AM
Yea. It’s more or less the same options you have in KT as well
t

tipsy

01/20/2018, 11:41 AM
i know i can do the same in kotlin, but there are more options? you can do it via objects, companion objects, standalone fields, etc.. 🤔
k

kingsley

01/20/2018, 11:44 AM
Object/class/companion objects would be implementations, the same as your
new ClassHandler()
Fields/properties, standalone/within a class, would be the same as your
MyClass.fieldHandler
Functions/methods, bound or unbound, will be the same as your
MyClass::methodRefHandler
I can’t think of any other different way to achieve this asides what’s already mentioned
t

tipsy

01/20/2018, 11:49 AM
alright, thanks!
thought there would be more options, but maybe not