Reputation: 9404
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.
Upvotes: 0
Views: 243
Reputation: 863
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.
Upvotes: 2