Vince Emigh Vince Emigh - 4 months ago 16
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
kotlin.Boolean
and working with
vararg
parameters.

Question

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

Answer

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.

Comments