简体   繁体   English

Java Lambda到Kotlin

[英]Java Lambda to Kotlin

I'm building my code with Kotlin. 我正在用Kotlin构建我的代码。

I've stumbled upon a problem using Lambda in Kotlin with the following: 我偶然发现在Kotlin中使用Lambda时遇到了以下问题:

Java code: Java代码:

  ((UndertowEmbeddedServletContainerFactory) container)
        .addBuilderCustomizers(builder ->
        builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true));

Using common interface instantiation 使用通用接口实例化

((UndertowEmbeddedServletContainerFactory) container)
            .addBuilderCustomizers(new UndertowBuilderCustomizer() {
                @Override
                public void customize(Builder builder) {
                    builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true);
                }
            });

My code in Kotlin 我在Kotlin中的代码

val c: UndertowEmbeddedServletContainerFactory = (container as UndertowEmbeddedServletContainerFactory)
// Calling the Lambda
c.addBuilderCustomizers{ (b: Builder) -> b.setServerOption(UndertowOptions.ENABLE_HTTP2, true) }

It's giving me a syntax error: 它给了我一个语法错误:

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. 此行上有多个标记-仅允许在带括号的参数列表中传递值(如vararg)-无法推断此参数的类型。 Please specify it explicitly. 请明确指定。

What might be the correct syntax to this? 正确的语法可能是什么?

You need to help Kotlin compiler a bit and tell it what is the type of this lambda. 您需要稍微帮助Kotlin编译器,并告诉它此lambda的类型是什么。 This code should compile and work just fine: 这段代码应该可以编译并正常工作:

        c.addBuilderCustomizers(UndertowBuilderCustomizer{ it.setServerOption(UndertowOptions.ENABLE_HTTP2, true)})

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

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