Kotlin List tail function

Abdelrhman Talat picture Abdelrhman Talat · Mar 5, 2016 · Viewed 7.8k times · Source

I am trying to find a tail function in List<T> but I couldn't find any. I ended up doing this.

fun <T> List<T>.tail() = this.takeLast(this.size -1)

Is there a better way to do this?

Answer

Vladimir Mironov picture Vladimir Mironov · Mar 5, 2016

Kotlin doesn't have a built-in List<T>.tail() function, so implementing your own extension function is the only way. Although your implementation is perfectly fine, it can be simplified a bit:

fun <T> List<T>.tail() = drop(1)

Or, instead of extension function, you can define an extension property:

val <T> List<T>.tail: List<T>
  get() = drop(1)

val <T> List<T>.head: T
  get() = first()

And then use it like:

val list = listOf("1", "2", "3")
val head = list.head
val tail = list.tail