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

后端 未结 1 1097
陌清茗
陌清茗 2021-01-19 16:25

In Scala, there is a convenient convention of providing collection factory methods through companion objects, using the companion object\'s apply method. So, i

相关标签:
1条回答
  • 2021-01-19 17:05

    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)
    
    0 讨论(0)
提交回复
热议问题