When calling methods from a Java API that expect SAM (single abstract method) type arguments is there a consistent way to coerce a function literal to the correct type? I'm finding that sometimes Kotlin functions work just fine and others not without any seeming consistency.
I have a couple of examples from the Ratpack API:
When calling ChainAction.handler(String, Handler)
using a Kotlin function literal works fine, e.g.:
handler("foo") { context -> context!!.render("from the foo handler") }
Type inference picks up that context
is a ratpack.handling.Context?
correctly.
On the other hand I'm trying to call Guice.handler(LaunchConfig, Action<? super ModuleRegistry>, Action<? super Chain>)
and can't figure out how to get a Kotlin function to stand in for the second argument. Is this down to the generic type making life difficult?
Maybe I'm expecting Kotlin to do something that it's not designed for but the first example shows that at least some SAM type coercion is possible (Kotlin fun to Ratpack Handler
).
This is a temporary problem with type projections (Java's ? super Foo
is translated into a type projection in Kotlin). Will be fixed in near future.
Tip: In difficult cases you can use "SAM adapters", e.g. Action<in Foo> { bar() }
to specify types explicitly