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?
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?
If working with non mutable lists, it is perfectly safe, and less memory consuming, to use simply :
fun <T> List<T>.tail(): List<T> =
if (isEmpty()) throw IllegalArgumentException("tail called on empty list")
else subList(1, count())
If you need both head and tail (which is a basic sequence operation) and don't eagerly consumed stream, you might want to have a sequence.
fun <T> Sequence<T>.headTail() =
HeadTailSequence(this)
.let { it.head to it.iterator.asSequence() }
private class HeadTailSequence<T>(parent: Sequence<T>) : Sequence<T> {
val iterator = parent.iterator()
val head: T? = iterator.next()
override fun iterator(): Iterator<T> {
return object : Iterator<T> {
override fun hasNext(): Boolean = iterator.hasNext()
override fun next(): T = if (iterator.hasNext()) throw NoSuchElementException() else iterator.next()
}
}
}
An extention for Iterable can be done in a similar manner.