Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing Java Interface - Kotlin

Tags:

java

kotlin

Just getting started with Kotlin and and I have read the official documentation, I am having issues implementing an interface from a library in kotlin.

Here is the interface in java :

public interface ResultCallBack {
    void detailsRetrieved(Obj var1, AnotherInterface var2);

    void anotherDataRetrieved(int var1, AnotherInterface var2);
}

the method I am calling from kotlin is like this :

 public static void startLibActivity(Context context, ResultCallBack callback) {
        sLuhnCallback = callback;
        context.startActivity(new Intent(context, Library.class));
    }

how do i call startLibActivity from kotlin and implement ResultCallBack as well

I think I am stuck with this trial :

Library.startLibActivity(activity, {})

I have tried many possibilities within {} , still having issues with the right implementation.

like image 422
Nosakhare Belvi Avatar asked Oct 16 '25 16:10

Nosakhare Belvi


1 Answers

Since your java interface is not a SAM Functional Interface, so you can't using lambda expression {} in Kotlin directly.

You can implement a Java interface in Kotlin, for example:

class KotlinResultCallBack : ResultCallBack {
    override fun detailsRetrieved(var1: Obj?, var2: AnotherInterface?) = TODO()

    override fun anotherDataRetrieved(var1: Int, var2: AnotherInterface?) = TODO()
}

Then you can call the startLibActivity method as below:

startLibActivity(context, KotlinResultCallBack())

You can also use an object expression to create an anonymous class instance which implements a Java interface, for example:

startLibActivity(context, object : ResultCallBack {
    override fun detailsRetrieved(var1: Obj?, var2: AnotherInterface?) = TODO()

    override fun anotherDataRetrieved(var1: Int, var2: AnotherInterface?) = TODO()
})
like image 94
holi-java Avatar answered Oct 18 '25 06:10

holi-java



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!