Skip to content

Instantly share code, notes, and snippets.

@roschlau
Created March 19, 2018 16:18
Show Gist options
  • Save roschlau/8434f69271798d092e54125d8741127c to your computer and use it in GitHub Desktop.
Save roschlau/8434f69271798d092e54125d8741127c to your computer and use it in GitHub Desktop.
Some helpers for working with immutable collections in Kotlin
/**
* Returns a new List with the element at [fromIndex] moved to [toIndex]
*/
private fun <T> List<T>.move(fromIndex: Int, toIndex: Int) = this.mapIndexed { index, element -> when {
index == toIndex -> this[fromIndex]
fromIndex < toIndex && index in fromIndex..toIndex -> this[index + 1]
fromIndex > toIndex && index in toIndex..fromIndex -> this[index - 1]
else -> element
} }
/**
* Returns a pair of the head and the tail of this iterable.
*/
fun <T> Iterable<T>.pop(): Pair<T, List<T>> = this.first() to this.drop(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment