Search code examples
javakotlindictionarylambdaforeach

How is Kotlin's Map.foreach better than the Java one?


A very simple example:

val map = mapOf("one" to 1, "two" to 2)
map.forEach{k, v -> if (k == "one") println(v)}  //Java API
map.forEach{(k, v) -> if (k == "two") println(v)}  //Kotlin extension

I am confused by the IDE warning Java Map.forEach method call should be replaced with Kotlin's forEach for the second line. I don't understand why should I replace it. They seem to work identically, and the only difference is the java method requiring 2 less symbols to type. Any ideas?


Solution

  • If nothing else, it's an inline function, and can more efficiently do things like mutate state elsewhere or smoothly incorporate suspend functions.

    Using the same forEach everywhere is simpler than having to track which one you're using at any given point.