mapOf() vs emptyMap() in Kotlin

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?

2

1 Answer

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.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like