Removing the last item in a List

Sometimes you need to remove one or more items from a collection, such as a List. Kotlin provides a few options to do such a thing, either in a static (remove last x items from the list) or in a more dynamic way (for example, remove items while the element doesn’t yet match a certain criteria).

val list = (1..6).toList()
val shorterList = list.dropLast(2)

assert(shorterList == listOf(1, 2, 3, 4))

val halfList = list.dropLastWhile { it > 3 }
assert(halfList == listOf(1, 2, 3))

Unfortunately, there is no default value for dropLast, so if you want to remove only the last item in the list, you have to be explicit by calling dropLast(1).

Leave a Reply

Your email address will not be published. Required fields are marked *