11

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?

piotrek
  • 13,982
  • 13
  • 79
  • 165

3 Answers3

17

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

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

See: Lambda Expression Syntax

hotkey
  • 140,743
  • 39
  • 371
  • 326
5

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() })
Todd
  • 30,472
  • 11
  • 81
  • 89
4

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.

s1m0nw1
  • 76,759
  • 17
  • 167
  • 196