Search code examples
kotlinlanguage-design

Why kotlin introduced "global notation" `listOf()` instead of static factory `List.of()` functions like Java?


To create a collections in Kotlin we can use listOf()/mapOf()/arrayOf() factory functions. Those functions are defined in "global notation" compared to Java's static factory notation: List<>.of().

In my opinion the Java's method of creating static collections is more intuitive and encourages better programming practices. Kotlin's way seems like a poor decision - names of functions are implicitly bound to the type they're returning. It contradicts the clarity point of Kotlin.

Why did Kotlin devs decide that it would be better to use listOf() mutableListOf() instead of List.of() and MutableList.of()?

I've read this question already, but the answers aren't satisfactory - there is no info about WHY it exists in the form it does and what benefits it has over simple static factory-style methods.


Solution

  • From historical point of view, Kotlin was officially released and introduced that notation in 2016, before List.of arrived to Java in 2017 (with Java 9). So, there was no obvious instead.

    Syntactically, List.of is implemented as a static function in List interface. Since there is no static keyword in Kotlin, it should be implemented as overloaded methods (for zero, one and several (vararg) parameters) of companion object. That will lead to GETSTATIC + INVOKEVIRTUAL calls instead of simple INVOKESTATIC (in global listOf case).