0

This is my kotlin class:

class example {

    var a = 0

    fun add(b: Int, callback: (Int) -> Unit){
        a += b
        callback(a)
    }
}

How do I use this function in a java code?

1
  • You initialize the class and then you can access inner methods. Commented Jan 9, 2020 at 18:32

1 Answer 1

8

Edit: As @Drawn Raccoon mentioned in the comments, you can call the add method from java code simply by returning Unit.INSTANCE:

Java:

example e = new example();
e.add(16, a -> {
    // do some work with 'a'
    return Unit.INSTANCE;
});

Or call it from kotlin without returning any value:

Kotlin:

add(16) {
    a -> // do some work with 'a'
}

Not correct(for correct answer refer to Edit section):

I think you can't use Unit type for output type of callback that will be called from java code. Unit is not recognized in Java. Instead you can use Void? (I don't know about 'Void' and now I can't test it).

Code in kotlin:

class example {

    var a = 0

    fun add(b: Int, callback: (Int) -> Void?){
        a += b
        callback(a)
    }
}

And calling it from java:

example e = new example();
e.add(16, a -> {
    // do some work with 'a'
    return null;
})

And call from kotlin:

val example = example()
e.add(16, { a ->
    // do some work with 'a'
    null
})

[ In addition, the 'example' is not a good name for kotlin or java classes and try to use upper case, like 'Example' ]

Sign up to request clarification or add additional context in comments.

4 Comments

"I think you can't use Unit" - it's not true, "Unit is not recognized in Java" - and it's not true. Unit is recognized in Java as Void/void automatically
@DrawnRaccoon You are right. Unit is recognized in Java. But as far as I know we can not return a Unit value from java. Can we? [If we could return a Unit value from java then we could call the callback given in the question]
do the same as with Void, return null;
also we can return Unit.INSTANCE;

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.