Reputation: 1187
Just started using Kotlin in our projects. To initialise an immutable map or list (possibly any collections in Kotlin) I could see two options mapOf()
and emptyMap()
(listOf()
and emptyList()
for a list).
Basically, the mapOf
is nothing but an inline function that returns emptyMap()
.
@kotlin.internal.InlineOnly
public inline fun <K, V> mapOf(): Map<K, V> = emptyMap()
What is preferred over another and why does Kotlin expose both?
Upvotes: 3
Views: 4090
Reputation: 190
It's a specialized overload of mapOf(vararg Pair<K, V>)
- there is no need to perform the size check if you're calling that function without any arguments.
As for "what's preferred over another" - whatever makes the code it's used in more readable. Performance-wise, there's no difference (as mapOf()
is inline), though for the sake of consistency you might want to choose one and stick with it.
Upvotes: 8