I have a question about jetpack compose modifier. I can't understand foldin and foldout, what are them and when I can use them? Thank you
A little bit of theory
In Kotlin, there are fold()
and foldRight()
functions, that allow a developer to accumulate a value starting with initial value
and applying operation left -> right
(or right -> left
, respectively) to current accumulator value and each element. Let's look at this with two examples:
val banknotes = listOf(1, 5, 10, 20)
// function starts folding with initial value 0
// it aggregates all add operations from left to right
banknotes.fold(0) { total, banknote -> total + banknote } // $36
// 1 + 5 = 6
// 6 + 10 = 16
// 16 + 20 = 36
// the second function works in reverse, or right to left
banknotes.foldRight(0) { total, banknote -> total + banknote } // $36
// 20 + 10 = 30
// 30 + 5 = 35
// 35 + 1 = 36
Modifier's .foldIn()
and .foldOut()
functions
In Jetpack Compose, the Modifier
companion object has two functions among others. The first one accumulates a value starting with initial value and applying operation to the current value and each element from outside in. The second function accumulates a value starting with initial value and applying operation to the current value and each element from inside out. Sounds familiar, hah?
.foldIn()
function may be used to accumulate a value starting from the parent or head of the modifier chain to the final wrapped child.
fun <R> foldIn(initial: R, operation: (R, Element) -> R): R
.foldOut()
function may be used to accumulate a value starting from the child or tail of the modifier chain up to the parent or head of the chain.
fun <R> foldOut(initial: R, operation: (Element, R) -> R): R
The only difference between the Modifier's functions and the above Kotlin's functions is that they can be used to determine the order in which modifications are applied. So foldIn()
and foldOut()
are rather auxiliary functions and in 99.99% of cases you will not use them.
Modifier
.background(Color.DarkGray)
.padding(20.dp)
.offset(x = 50.dp)
.foldIn(Unit) { _, element ->
println(element::class.simpleName)
}
Prints:
// BackgroundElement
// PaddingElement
// OffsetElement
© 2022 - 2025 — McMap. All rights reserved.