Created
March 19, 2018 16:18
-
-
Save roschlau/8434f69271798d092e54125d8741127c to your computer and use it in GitHub Desktop.
Some helpers for working with immutable collections in Kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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