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?
In Kotlin, lambda expressions are always surrounded by curly braces, so it's
myClass.mapToEntry({ r -> r }, { r -> r })
See: Lambda Expression Syntax
Basic Syntax: Lambda expressions are always wrapped in curly braces:
val sum = { x: Int, y: Int -> x + y }
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.
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() })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With