Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Kotlin use `List(...)` as a factory for lists and a similar convention for all abstract collections?

Tags:

kotlin

In Scala, there is a convenient convention of providing collection factory methods through companion objects, using the companion object's apply method. So, if I want to create a list with the elements 1, 2, and 3, I just use List(1, 2, 3). The pattern is consistent across all collection types.

In Kotlin, if I write List(1, 2, 3) I get a compilation error. To create a list with 1, 2, and 3, one has to use listOf(1, 2, 3). List is an interface, so it has no constructor, obviously. There could have been a companion object but there isn't one. There is a List function, though with a different signature than what one would expect coming from Scala (public inline fun <T> List(size: Int, init: (index: Int) -> T): List<T>).

So, why did the Kotlin collection library designers choose not to follow a uniform convention for collection factories similar to the one in Scala?

like image 538
pvillela Avatar asked Dec 14 '22 19:12

pvillela


1 Answers

why did the Kotlin collection library designers choose not to follow a uniform convention for collection factories

There's a "uniform convention": Use the Kotlin standard library functions listOf, arrayOf, mapOf etc., as stated in the docs:

Kotlin does not have dedicated syntax constructs for creating lists or sets. Use methods from the standard library, such as listOf(), mutableListOf(), setOf(), mutableSetOf()

I’m not sure why the Scala approach would actually be any better. If you like to have those constructor-like functions anyway, it's not a big deal to create them:

fun <T> List<T>(vararg e: T) = listOf(e)

//use it
val l = List(1, 2, 3, 4)
like image 157
s1m0nw1 Avatar answered Dec 18 '22 00:12

s1m0nw1