爪哇Lambda至Kotlin
我正在用Kotlin建立我的代码
我在Kotlin中使用Lambda时遇到以下问题:
Java代码:
((UndertowEmbeddedServletContainerFactory) container)
.addBuilderCustomizers(builder ->
builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true));
使用公共接口实例化
((UndertowEmbeddedServletContainerFactory) container)
.addBuilderCustomizers(new UndertowBuilderCustomizer() {
@Override
public void customize(Builder builder) {
builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true);
}
});
我在Kotlin的代码
val c: UndertowEmbeddedServletContainerFactory = (container as UndertowEmbeddedServletContainerFactory)
// Calling the Lambda
c.addBuilderCustomizers{ (b: Builder) -> b.setServerOption(UndertowOptions.ENABLE_HTTP2, true) }
这给了我一个语法错误:
Multiple markers at this line - Passing value as a vararg is only allowed inside a parenthesized argument list - Cannot infer a type for this parameter. Please specify it explicitly.
正确的语法可能是什么
# 1 楼答案
您需要稍微帮助Kotlin编译器,并告诉它这个lambda的类型。这段代码应该可以编译并正常工作: