0

Is there a way to access the last element of a List using a special index like in python where -1 return the last element? avoiding to write extra code like list.size - 1. An example of the python way here.

I've tried following but doesn't work:

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

    println(numbers[-1])
}

Any help or explanation will be appreciated.

SvMax
  • 157
  • 2
  • 10
Sam Chen
  • 7,597
  • 2
  • 40
  • 73
  • 2
    In Java: `numbers.get(numbers.size() - 1)`. In Kotlin, I do not know. – Seelenvirtuose Oct 16 '20 at 14:31
  • what's wrong with `size - 1`? It's direct index too – Sergey Glotov Oct 16 '20 at 14:31
  • @Sergey Glotov I want a more simpler like just `-1` in Python, just curious that if is it possible. – Sam Chen Oct 16 '20 at 14:35
  • 2
    `numbers[numbers.lastIndex]` or `numbers.last()`, what you intend to use this for exactly? – IR42 Oct 16 '20 at 14:36
  • 2
    Most languages, including Kotlin, don't have this notation. It's in Python and Perl. Kotlin is interoperable with Java, so it probably wasn't even an option to include it because of the behavior change. A negative index in Java will give you an IndexOutOfBoundsException. – Tenfour04 Oct 16 '20 at 15:08

1 Answers1

4

You could use numbers.lastIndex:

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