Vince Emigh Vince Emigh - 1 year ago 102
Java Question

Kotlin's Higher-Order Functions in Java project

I have a function that has a function type as a formal parameter:

fun doSomething(code: () -> Boolean) = false //package function in TestKt.class

I've tried calling it in Java, passing in a lambda:

//Java class, in Java project
class Demo {
public static void main(String[] args) {
TestKt.doSomething(() -> false);

But I get the error:

Cannot infer functional interface type

It works when the Java class is in a Kotlin project, but not in a Java project. I haven't had problems with anything else while using classes from Kotlin in my Java project, such as using kotlin methods typed with
and working with


How do I properly call the
function from a Java project?

Answer Source

The environment must support the Kotlin API.

If the environment has restrictions on 3rd party libraries, and does not support the Kotlin API, you will not be able to use Kotlin in that environment.

I came back to this issue and finally found the problem. The environment I was working restricted third-party libraries, which prevented me from using the Kotlin API.

It's due to Kotlin using it's own types for primitives (such as Boolean). At first, I thought those types would be compiled into Java primitive wrappers to ensure full interop. But apparently it still uses the Boolean from the Kotlin API.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download