4

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?

pvillela
  • 553
  • 1
  • 6
  • 10
  • 2
    We could equally turn the headline question around - why *should* Kotlin have a List(...) creation method? What do you mean by "uniform"? Note also that there is more than one creation method - listOf, mutableListOf, etc. – Oliver Charlesworth Dec 30 '17 at 14:35
  • An [answer](https://stackoverflow.com/a/34752211/8343333) from another post explains why it is not a good practice to have a factory function name same as the class's one. In case of interface or abstract class, it is better to have consistent naming style of factory function for class, interface and abstract class. – BakaWaii Dec 30 '17 at 15:37
  • 2
    @BakaWaii Except, as the question mentions, there _is_ a factory function with the same name in the Kotlin library. – Alexey Romanov Dec 30 '17 at 18:29

1 Answers1

12

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)
s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
  • You've explained how but you have not explained why. This isn't just a random choice. Kotlin promotes distinguishing between mutable and immutable collections as a feature. They want the idea of what is mutable to be obvious in all cases. As an example this is why parameters are immutable. https://kotlinlang.org/docs/reference/collections.html –  Sep 07 '18 at 00:47
  • No this is totally unrelated to this question imho – s1m0nw1 Sep 07 '18 at 07:53