为什么Kotlin不使用`List(...)`作为列表的工厂和所有抽象集合的类似约定? [英] Why doesn't Kotlin use `List(...)` as a factory for lists and a similar convention for all abstract collections?

查看:75
本文介绍了为什么Kotlin不使用`List(...)`作为列表的工厂和所有抽象集合的类似约定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Scala中,有一个方便的约定,即使用伴随对象的apply方法通过伴随对象提供收集工厂方法.因此,如果要创建包含元素1、2和3的列表,则只需使用List(1, 2, 3).该模式在所有馆藏类型中都是一致的.

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.

在Kotlin中,如果我写List(1, 2, 3),则会出现编译错误.要创建包含1、2和3的列表,必须使用listOf(1, 2, 3). List是一个接口,因此显然没有构造函数.可能有一个同伴对象,但没有一个.有一个List函数,尽管它的签名与Scala(public inline fun <T> List(size: Int, init: (index: Int) -> T): List<T>)的签名不同.

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>).

那么,为什么Kotlin馆藏设计师不选择类似于Scala中的馆藏工厂的统一惯例?

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

推荐答案

为什么Kotlin馆藏设计师不选择对馆藏工厂遵循统一的惯例

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

有一个统一约定":使用Kotlin标准库函数listOfarrayOfmapOf等,如

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

Kotlin没有用于创建列表或集合的专用语法构造. 使用标准库中的方法,例如listOf()mutableListOf()setOf()mutableSetOf()

我不确定为什么Scala方法会更好.如果您仍然希望拥有那些类似于构造函数的函数,那么创建它们就没什么大不了的:

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不使用`List(...)`作为列表的工厂和所有抽象集合的类似约定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆