简体   繁体   中英

Using Kotlin function as Java SAM type

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, eg:

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", eg Action<in Foo> { bar() } to specify types explicitly

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM