在< Int>Kotlin中使用List解构

eoigrqb6  于 2023-05-07  发布在  Kotlin
关注(0)|答案(2)|浏览(173)

如何解构传递给Kotlin函数的List?

问题:

我不想向函数传递一个复杂的参数列表,而是想传递一个List并在函数体中解构它。下面的代码不起作用,所以我恢复到提取每个变量(下面的简化代码示例)-建议?

val (h1, m1, s1, h2, m2, s2) = timeData

问题:

将timeData分解为一组值的正确方法是什么?

简化代码示例:

import java.util.Scanner

const val HOURS = 3600
const val SECONDS = 60

fun secondsBetweenTwoMoments(timeData: List<Int>): Int {
    require(timeData.size == 6) { "List must have exactly 6 elements" }
    val h1 = timeData[0]
    val m1 = timeData[1]
    val s1 = timeData[2]
    val h2 = timeData[3]
    val m2 = timeData[4]
    val s2 = timeData[5]

    // Convert moment 1 and 2 to seconds
    val seconds1 = h1 * HOURS + m1 * SECONDS + s1
    val seconds2 = h2 * HOURS + m2 * SECONDS + s2
    return seconds2 - seconds1
}

fun main() {
    val scanner = Scanner(System.`in`)
    val inputs = mutableListOf<Int>()
    repeat(6) {
        inputs.add(scanner.nextInt())
    }
    val seconds = secondsBetweenTwoMoments(inputs)
    println(seconds)
}

总结一下,“先生,我发现了一个有趣的魔术...”

mwkjh3gx

mwkjh3gx1#

您已经达到了标准库为List定义的解构运算符函数的数量限制。你可以再添加一个,然后解构代码就可以工作了:

operator fun <T> List<T>.component6(): T = get(5)

至于为什么他们只内置了最多5个元素的解构,我认为这是因为除此之外,它变得有点脆弱/不可读,你可能想考虑使用一个专门的数据类,而不是一个列表。
我不知道你为什么要提到类型转换,因为你的代码中没有类型转换。

q5iwbnjs

q5iwbnjs2#

解决方案

基于@Tengfour04的回答(谢谢)...这里有两种可能的方法--为了清楚起见而公布。
引文:

示例代码

import java.util.Scanner

const val HOURS = 3600
const val SECONDS = 60

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

fun secondsBetweenTwoMoments(timeData: List<Int>): Int {
    val (h1, m1, s1, h2, m2, s2) = timeData

    // Convert moment 1 and 2 to seconds
    val seconds1 = h1 * HOURS + m1 * SECONDS + s1
    val seconds2 = h2 * HOURS + m2 * SECONDS + s2
    return seconds2 - seconds1
}

fun secondsBetweenTwoMoments2(timeData1: List<Int>,
                              timeData2: List<Int> ): Int {
    val (h1, m1, s1) = timeData1
    val (h2, m2, s2) = timeData2

    // Convert moment 1 and 2 to seconds
    val seconds1 = h1 * HOURS + m1 * SECONDS + s1
    val seconds2 = h2 * HOURS + m2 * SECONDS + s2
    return seconds2 - seconds1
}

fun main() {
    val scanner = Scanner(System.`in`)
    val inputs = mutableListOf<Int>()
    repeat(6) {
        inputs.add(scanner.nextInt())
    }

    val seconds = secondsBetweenTwoMoments(inputs)
    println(seconds)

    val seconds2 = secondsBetweenTwoMoments2(inputs.subList(0,3),
                                             inputs.subList(3,6))
    println(seconds2)
}

相关问题