Running into a kotlin/Java snafu. Received a libra...
# announcements
d
Running into a kotlin/Java snafu. Received a library written in Kotlin, and the app thats going to use the library is all in Java and there is no plan to introduce Kotlin to that app....yet. The Kotlin library has a public api similar to
fun doBar(callBack: (String, Array<Int>) -> Unit)
. That gets exposed to Java as
doBar(Function2<? super String, ? super Integer[], Unit> callback)
. When ever we try to create a anonymous class of Function2 we get
Copy code
doBar(Function2<? super String, ? super Integer[], Unit> callback) cannot be applied to (anonymous Function2< String, Integer[], Unit>)
. Is there another way to call a kotlin function interface from Java?
I know the easy fix for this is to use a interface as a callback in the function parameter, but this library was created from a Kotlin MPP project that targets iOS also. The current api allows lamba calling conventions in Kotlin, iOS and Objective-C. Its only java right now that will have to call it differently. If we changed to use an interface, all languages would have to use a different calling convention....which we would like to avoid. So....besides switching the function signature to use a custom interface, is there another way to call it using Kotlins Function interface?
c
Copy code
doBar((s, integers) -> {
	System.out.println(s);
	System.out.println(integers.length);
	return null;
});
If it's a lambda why bother creating anonymous class of Function2? You should take advantage of Java SAM conversion and use Java lambda.
☝️ 1
If you insist on an anonymous class though, it should work too:
Copy code
doBar(new Function2<>() {
	@Override
	public Unit invoke(String s, Integer[] integers) {
		System.out.println(s);
		System.out.println(integers.length);
		return null;
	}
});
d
@Czar good call, on calling vial Sam conversion however the compiler complains
Copy code
Function2<? super String, ? super Integer[], Unit> is not a functional interface
c
I've actually tested it and it works. Maybe something is wrong with your project setup? If I define
doBar
as
Copy code
fun doBar(callback: (String, Array<Int>) -> Unit) {
	callback("vasya", arrayOf(1,2,3))
}
Then the java code above does indeed print:
Copy code
> Task :TstJ.main()
vasya
3
d
Thanks for confirming. I'll double check our setup and see if I can find out whats going on lol.
👍 1