More advanced fold methods for Kotlin, for use only after mastering:
do {} while()
fold
foldRight
foldRightIndexed
The library is available as Maven artifact on Maven Central. The latest version number can be found there or from the latest GitHub release. You can use it as a dependency in your project, for example using Gradle (Kotlin DSL):
repositories {
mavenCentral()
}
dependencies {
implementation("org.eend:fold:x.y.z")
}
foldSandwich
foldSandwichIndexed
foldSandwichNullable
Accumulates the lambda result based on the initial value, while simultaneously providing the first and last item of the list, working inwards towards the center of the list.
If there is an odd number of items, the center item is not provided and is thus lost.
An alternative for this is using foldSandwichNullable
, which keeps the center item but also
adds a null value.
Usage
val list = listOf("S", "n", "w", "c", "h", "i", "d", "a")
val foldedSandwich = list.foldSandwich("") { first: String, currentValue: String, last: String ->
"$currentValue$first$last"
}
println(foldedSandwich) // Prints: "Sandwich"
foldZigzag
foldZigzagIndexed
Accumulates the lambda result based on the initial value, while alternating between the first and last item of the list. Starts with the first item.
Usage
val list = listOf("Z", "g", "a", "g", "z", "i")
val result = list.foldZigzag("") { currentValue: String, next: String ->
"$currentValue$next"
}
println(result) // Prints: "Zigzag"
foldRandom
foldRandomIndexed
Accumulates the lambda result based on the initial value, while randomly picking the next item. It is guaranteed that all items are provided to the lambda.
Usage
val list = listOf("R", "a", "n", "d", "o", "m")
val result = list.foldRandom("") { currentValue: String, next: String ->
"$currentValue$next"
}
println(result) // Prints one of: "admonR", "naRdmo", "danomR", and so on.
foldChaos
Better do not use this one. It is guaranteed to cause a mess.
Usage
val list = listOf("C", "h", "a", "o", "s", 5)
val result = list.foldChaos("") { acc, next ->
acc + next
}
println(result) // Different result every time, for example: sBgVogd-1207019598hs5o