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?
CodePudding user response:
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.
CodePudding user response:
In addition to other answers: the Java method is only available in Kotlin/JVM, while the Kotlin function is cross-platform and can also be used in Kotlin/Native and Kotlin/JS. So without good reasons to use the Java version, it makes sense to default to the Kotlin version with its greater compatibility.
CodePudding user response:
In Kotlin, the forEach
function on the Map
class is an extension function that provides a more concise and readable syntax for iterating over the key-value pairs in a map.
Here is an example of how you might use the forEach
function in Kotlin to print out the key-value pairs in a map:
val map = mapOf("a" to 1, "b" to 2, "c" to 3)
map.forEach { key, value ->
println("$key -> $value")
}
This code will print out the following:
a -> 1
b -> 2
c -> 3
In Java, you can iterate over the key-value pairs in a map using the forEach
method of the Map.Entry
interface, but the syntax is more verbose and less readable:
Map<String, Integer> map = Map.of("a", 1, "b", 2, "c", 3);
map.entrySet().forEach(entry -> {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key " -> " value);
});
This code will produce the same output as the Kotlin example