我有一个JSON数组,它包含五个以上的元素。
试图做以下工作:
val (a, b, c, d, e, f, g) = JSON.array()这将引发以下错误:
Kotlin: Destructuring declaration initializer of type List<Letter> must have a 'component6()' function
Kotlin: Destructuring declaration initializer of type List<Letter> must have a 'component7()' function我不想编写以下代码:
val a = array[0], b = array[1] ...发布于 2018-12-01 19:18:52
我通过声明附加的componentN函数来解决这个问题:
operator fun List<Any>.component6() = this[5]
operator fun List<Any>.component7() = this[6]备注
如果我们想要使用析构声明,我们需要用data关键字标记这个类,或者为我们想要得到的多少值提供component1, component2 ... componentN函数。
对于List类,生成的_Collections.kt文件only包含compenentN函数直到compenent5为止。
发布于 2018-12-01 23:28:43
componentX函数用于List是在kotlin.collections包中定义的。您将为组件1至5创建找到它。如果您想拥有更多的组件,您可以创建像这样的扩展函数,这是基于已经提供的实际实现:
/**
* Returns 6th *element* from the collection.
*/
inline operator fun <T> List<T>.component6(): T = get(5)https://stackoverflow.com/questions/53574229
复制相似问题