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?
Yours and @Vladimir Mironov 's solutions will work, but they automatically create eager copies of the original list (sans the first element), which can take a very long time for larger lists. I would define it with a wrapper
List
class that delegates its methods to the wrapped one, ignoring the first element using index adjustments:You may notice the functions in the section after the comment still end up making an eager copy. I only did this for simplicity's sake. For memory's sake, I made a
lazy
tailList
propertyThey could all be implemented by iterating over the collection manually, rather than doing some sort of delegating. If that's what you'd prefer, I'm sure you can figure it out.
With that, the head and tail properties become this:
If you really need it, I can add an update to make the last three member functions so that they don't make eager copies.
EDIT: Note: If you followed the conventions that Kotlin has followed so far, you wouldn't make the
List
's tail be lazy, like this, since all of their functions onList
make eager copies. Instead, especially if you're usinghead
andtail
to recursively iterate over a list, I would see if you could attempt this wrapper idea onSequence
somehow.Sequence
's whole point of existence is for lazy work on collections.EDIT 2: Apparently sublist() creates a view, and is therefore already lazy. Essentially, I've just taught you how to create the implementation for sublist, except I narrowed it to only the tail.
So, in that case just use sublist() for your tail function.
If working with non mutable lists, it is perfectly safe, and less memory consuming, to use simply :
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:Or, instead of extension function, you can define an extension property:
And then use it like: