private val repositories = mutableListOf<String>()

private val repositories = ArrayList<String>()

Both are mutable list, then what is the point of two keywords mutableListOf or ArrayList?

or is there any major difference?

推荐答案

两者之间的唯一区别是传达你的意图.

When you write val a = mutableListOf(), you're saying "I want a mutable list, and I don't particularly care about the implementation". When you write, instead, val a = ArrayList(), you're saying "I specifically want an ArrayList".

实际上,在Kotlin编译到JVM的当前实现中,调用mutableListOf将生成ArrayList,行为上没有区别:一旦建立了列表,所有东西的行为都将相同.

Now, let's say that a future version of Kotlin changes mutableListOf to return a different type of list.

更有可能的是,Kotlin团队只有在他们认为新的实现更适合大多数用例的情况下才会做出改变.mutableListOf将让您透明地使用新的列表实现,您将免费获得更好的行为.如果听起来像你的案子,那就选mutableListOf吧.

On the other hand, maybe you spent a bunch of time thinking about your problem, and figured that ArrayList really is the best fit for your problem, and you don't want to risk getting moved to something sub-optimal. Then you probably want to either use ArrayList directly, or use the arrayListOf factory function (an ArrayList-specific analogue to mutableListOf).

Kotlin相关问答推荐

当通过firstOrders访问时,存储在伴随对象中的对象列表具有空值

等待下一个值时暂停Kotlin Coroutine

为什么Kotlin协程程序即使有延迟也能输出?

在 Kotlin 中将 Array 转换为 IntArray 时丢失值

在Kotlin lambda的参数中如何指定函数类型?

Android Jetpack Compose:在空的 Compose 活动中找不到 OutlinedTextField (Material3)

如何在 Spring Boot 3 中为内部类提供运行时提示

在 Kotlin 中,为什么在 `+` 之前但在 `.` 之前没有换行符?

如何为 Kotlin 中的每个循环设置以避免越界异常

Jetpack Compose - 单击 LazyColumn 的项目时应用程序崩溃

异常传播如何在 CoroutineScope.async 上工作?

在 APK META-INF/library_release.kotlin_module 中复制的重复文件

具有多个不同类型来源的 LiveData

如何禁用智能投射突出显示 Kotlin?

如何修复 ViewPager2 中的Design assumption violated错误?

Android Studio 4.0.0 Java 8 库在 D8 和 R8 构建错误中脱糖

使用 clear() 删除 EncryptedSharedPreferences 不起作用

RecyclerView SnapHelper无法显示第一个/最后一个元素

通过在 kotlin-gradle 中使用子项目Unresolved reference: implementation

Kotlin 中的限制函数