简体   繁体   中英

Setting a kotlin lambda from java

So say I have some simple data class like this:

data class Transaction(
    val time: Long,
    val sender: String,
    val data: ByteArray
)

And in Kotlin I have the following method defined:

fun handleTransaction(transactionGetter: ()->Transaction) {
    // do something
}

How do I go about calling this method from Java?

I've tried trying to make a java lambda but can't figure it out. It is telling me that the parameter is supposed to be a Function0<Transaction> but I am not too sure how to define that.


Okay so, I figured out I can do this:

handleTransaction(new Function0<Transaction>() {
    @Override
    public Transaction invoke() {
        // handle getting transaction           
    }
});

Is that really the right way to do it? It is quite ugly.

If you're targeting at least JDK 8, you can do this (if function handleTransaction is defined in file Transaction.kt ):

    public static void main(String[] args) {
        TransactionKt.handleTransaction(() -> new Transaction(
                Instant.now().toEpochMilli(), "system", new byte[0]));
    }

If you are targeting anything below JDK 8, then there is no other way other than what you already found.

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