简体   繁体   中英

How to read with java a callback from a kotlin class (Android)

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?

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' ]

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