【问题标题】:Best way to access last element of list in Kotlin [duplicate]在 Kotlin 中访问列表最后一个元素的最佳方法 [重复]
【发布时间】:2023-06-07 23:00:01
【问题描述】:

有没有办法使用特殊索引访问List 的最后一个元素,例如在 python 中 -1 返回最后一个元素?避免编写像list.size - 1 这样的额外代码。 python方式here的一个例子。

我试过以下但不起作用:

fun main() {
    val numbers = (1..5).toList()

    println(numbers[-1])
}

任何帮助或解释将不胜感激。

【问题讨论】:

  • 在 Java 中:numbers.get(numbers.size() - 1)。在 Kotlin 中,我不知道。
  • size - 1 有什么问题?也是直接索引
  • @Sergey Glotov 我想要一个更简单的,比如 Python 中的 -1,只是好奇是否可能。
  • numbers[numbers.lastIndex]numbers.last(),你打算用它来做什么?
  • 大多数语言,包括 Kotlin,都没有这种表示法。它在 Python 和 Perl 中。 Kotlin 可与 Java 互操作,因此由于行为变化,它甚至可能不是包含它的选项。 Java 中的负索引会给你一个 IndexOutOfBoundsException。

标签: java list kotlin


【解决方案1】:

你可以使用numbers.lastIndex:

fun main() {
    val numbers = (1..5).toList()
    println(numbers[numbers.lastIndex])
}

【讨论】: