简体   繁体   English

kotlin:2 lambda参数的语法

[英]kotlin: syntax for 2 lambda parameter

I'm new to kotlin. 我是kotlin的新手。 I have a java class with 2 overloaded methods. 我有一个带有2个重载方法的java类。 One accepts one function, the other one accepts two 一个接受一个功能,另一个接受两个功能

mapToEntry(Function<? super T, ? extends V> valueMapper)

and

mapToEntry(Function<? super T, ? extends K> keyMapper, 
           Function<? super T, ? extends V> valueMapper)

nowm in kotlin, i'm trying to call the the version with 2 parameters (as in java): nowm in kotlin,我试图调用带有2个参数的版本(如java中所示):

myClass.mapToEntry(r -> r, r -> r)

but i get compilation error. 但我得到编译错误。

Kotlin: Unexpected tokens (use ';' to separate expressions on the same line) Kotlin:意外的令牌(使用';'来分隔同一行上的表达式)

what's the correct syntax? 什么是正确的语法?

In Kotlin, lambda expressions are always surrounded by curly braces, so it's 在Kotlin中,lambda表达式总是被花括号括起来,所以就是这样

myClass.mapToEntry({ r -> r }, { r -> r })

See: Lambda Expression Syntax 请参阅: Lambda表达式语法

You were close, you just have to wrap them in curly braces... 你很亲密,你只需要用花括号包裹它们......

myClass.mapToEntry({r -> r}, {r -> r})

Also, you can take advantage of the fact that Kotlin defines it as the default single parameter to a lambda. 此外,您可以利用Kotlin将it定义为lambda的默认单个参数这一事实。 Assuming the key and value are both Strings, and you want to reverse the key and uppercase the value (just making up an example): 假设键和值都是字符串,并且您想要反转键和大写值(只是组成一个例子):

myClass.mapToEntry( { it.reversed() }, { it.toUpperCase() })

Basic Syntax : Lambda expressions are always wrapped in curly braces: 基本语法 :Lambda表达式始终用大括号括起来:

val sum = { x: Int, y: Int -> x + y }

Example

Let's define a function similar to yours in Kotlin: 让我们在Kotlin中定义一个类似于你的函数:

fun <T, K> mapToEntry(f1: (T) -> K, f2: (T) -> K) {}

The first possibily is straight forward, we simply pass two lambdas as follows: 一个可能是直截了当,我们简单地传递两个lambdas如下:

mapToEntry<String, Int>({ it.length }, { it.length / 2 })

Additionally, it's good to know that if a lambda is the last argument passed to a function, it can be lifted out the parantheses like so: 另外,最好知道如果lambda是传递给函数的最后一个参数,它可以像这样提取出parantheses:

mapToEntry<String, Int>({ it.length }) {
    it.length / 2
}

The first lambda is passed inside the parantheses, whereas the second isn't. 第一个lambda在parantheses内部传递,而第二个lambda不在。

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

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