Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kotlin: syntax for 2 lambda parameter

I'm new to kotlin. I have a java class with 2 overloaded methods. 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):

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

but i get compilation error.

Kotlin: Unexpected tokens (use ';' to separate expressions on the same line)

what's the correct syntax?

like image 896
piotrek Avatar asked Jan 11 '18 13:01

piotrek


3 Answers

In Kotlin, lambda expressions are always surrounded by curly braces, so it's

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

See: Lambda Expression Syntax

like image 186
hotkey Avatar answered Sep 27 '22 18:09

hotkey


Basic Syntax: Lambda expressions are always wrapped in curly braces:

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

Example

Let's define a function similar to yours in Kotlin:

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

The first possibily is straight forward, we simply pass two lambdas as follows:

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:

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

The first lambda is passed inside the parantheses, whereas the second isn't.

like image 35
s1m0nw1 Avatar answered Sep 27 '22 16:09

s1m0nw1


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. 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() })
like image 42
Todd Avatar answered Sep 27 '22 17:09

Todd