Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin List tail function

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?

like image 803
Abdelrhman Talat Avatar asked Mar 04 '16 23:03

Abdelrhman Talat


People also ask

How do I get list data on Kotlin?

To get the element from a List in Kotlin present at specific index, call get() function on this list and pass the index as argument to get() function. The Kotlin List. get() function returns the element at the specified index in this list.

How do I create a list of strings in Kotlin?

Inside main() , create a variable called numbers of type List<Int> because this will contain a read-only list of integers. Create a new List using the Kotlin standard library function listOf() , and pass in the elements of the list as arguments separated by commas.

What are extension functions in Kotlin?

Extension functions are a cool Kotlin feature that help you develop Android apps. They provide the ability to add new functionality to classes without having to inherit from them or to use design patterns like Decorator.


1 Answers

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 
like image 137
Vladimir Mironov Avatar answered Sep 24 '22 20:09

Vladimir Mironov