0

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.

3
  • 1
    Just like any other anonymous interface implementation. Commented Jan 24, 2020 at 16:42
  • 1
    () -> createTransaction() just like a Java Supplier<Transaction>. Commented Jan 24, 2020 at 16:48
  • @JBNizet ahhh, thanks Commented Jan 24, 2020 at 16:51

1 Answer 1

2

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.

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

Comments

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.