简体   繁体   中英

Implementing Java Interface - 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.

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()
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM