简体   繁体   English

使用Kotlin函数作为Java SAM类型

[英]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? 从Java API调用需要SAM(单个抽象方法)类型参数的方法时,是否存在一种将函数文字强制转换为正确类型的一致方法? I'm finding that sometimes Kotlin functions work just fine and others not without any seeming consistency. 我发现有时候Kotlin函数可以很好地工作,而其他函数似乎并没有任何一致性。

I have a couple of examples from the Ratpack API: 我有一些来自Ratpack API的示例:

When calling ChainAction.handler(String, Handler) using a Kotlin function literal works fine, eg: 当使用Kotlin函数文字调用ChainAction.handler(String, Handler)可以正常工作,例如:

handler("foo") { context -> context!!.render("from the foo handler") }

Type inference picks up that context is a ratpack.handling.Context? 类型推断表明contextratpack.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. 另一方面,我试图调用Guice.handler(LaunchConfig, Action<? super ModuleRegistry>, Action<? super Chain>) ,却不知道如何让Kotlin函数代替第二个参数。 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 ). 也许我希望Kotlin可以完成并非为特定目的而设计的工作,但第一个示例表明,至少可以进行某些 SAM类型的强制转换(对于Ratpack Handler是Kotlin的乐趣)。

This is a temporary problem with type projections (Java's ? super Foo is translated into a type projection in Kotlin). 这是类型投影的一个临时问题(Java的? super Foo在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 提示:在困难情况下,可以使用“ SAM适配器”,例如Action<in Foo> { bar() }明确指定类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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