4

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.

3
  • What did you tried? Commented Jul 10, 2017 at 16:17
  • What does your Kotlin code look like? Commented Jul 10, 2017 at 16:19
  • @Makoto I just updated the question Commented Jul 10, 2017 at 16:22

1 Answer 1

9

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()
})
Sign up to request clarification or add additional context in comments.

2 Comments

thanks. This works ! Will accept the answer in 5 mins
@belvi Not at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.