我有一个正则表达式的结果,它将七个捕获组返回到一个数组中.

我以为我会使用解构,而不是使用数组元素的下标来构造我的对象,问题是我似乎只能有五个组件.

A minimal example:

//  val (a, b, c, d, e) = listOf(1, 2, 3, 4, 5)
val (a, b, c, d, e, f, g) = listOf(1, 2, 3, 4, 5, 6, 7)

Compiler output:

> Error:(70, 41) Kotlin: Destructuring declaration initializer of type
> List<Int> must have a 'component6()' function 
> Error:(70, 41) Kotlin: Destructuring declaration initializer of type 
> List<Int> must have a 'component7()' function

有没有办法拥有五个以上的组件,或者这是最大值?

推荐答案

List接口只定义了5个组件函数(作为扩展函数).

You can add your own component functions as extension functions:

operator fun <T> List<T>.component6() = this[5]
operator fun <T> List<T>.component7() = this[6]
// ...

This would work now:

val (a, b, c, d, e, f, g) = listOf(1, 2, 3, 4, 5, 6, 7)

docs人中:

当然,也可以有component3()和component4()等等.

Note that the componentN() functions need to be marked with the operator keyword to allow using them in a destructuring declaration.

Kotlin相关问答推荐

如何在Jetpack Compose中的列中渲染图像

我如何测试一个可组合组件没有显示,但如果它不存在也接受?

何时使用figureEach

在Kotlin项目中使用Free Fair AspectJ插件(使用Gradle)

如何检测一个值是否是Kotlin中的枚举实例?

哪个更好? Integer.valueOf(readLine()) 或 readLine()!!.toInt()

协程子作业(job)取消

Kotlin 中私有集的完整语法 struct 是什么?

如何在 Compose 中创建可重用的修饰符?

Dagger 2 ContributesAndroidInjector 为模块提供活动

无法删除部分子项.这可能是因为进程打开了文件或将其工作目录设置在目标目录中

对列表中数字的子集求和

如何在 Kotlin 中使用 volatile

如果我可以将 Flow 和 StateFlow 与生命周期范围 \ viewLifecycleOwner.lifecycleScope 一起使用,那么在 ViewModel 中使用 LiveData 有什么意义

如何暂停kotlin coroutine直到收到通知

重复构建失败To use Coroutine features, you must add `ktx`......

android Room 将 Null 作为非 Null 类型返回

内联 onFocusChange kotlin

你如何在 Kotlin 中注释 Pair 参数?

如何在 Kotlin 中按字母顺序对字符串进行排序