Why doesn't Kotlin use `List(…)` as a factory

2020-04-10 02:46发布

问题:

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?

回答1:

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)


标签: kotlin