12

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?

3 Answers 3

18

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

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

See: Lambda Expression Syntax

Sign up to request clarification or add additional context in comments.

Comments

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() })

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.