Search code examples
kotlinlambdaandroid-jetpack-composedeclaration

kotlin - unknown syntax in Jetpack Owl Example


trying to find some direction on how to select multiple items in a lazy column, I have found the following code in Owl Jetpack Compose example (Onboarding.kt).

...    
val (selected, onSelected) = remember { mutableStateOf(false) }
...

Even if I'm able to use the code by myself, I really not able to decode the syntax of this val declaration. I wasn't able to find anything in kotlinlang.org site (the nearest topic I've found is about Destructuring declarations). Could someone help me to understand it and/or point me to relevant documentation?


Solution

  • This syntax is Destructuring as you mentioned in question which is expclicitly as

    val (selected: Boolean, onSelected: (Boolean) -> Unit) = remember { mutableStateOf(false) }
    

    Which requires 2 components of targetted class. (val num1:Int, val num2:Int) = Pair(1,2) is an example

    With MutableState

    @Stable
    interface MutableState<T> : State<T> {
        override var value: T
        operator fun component1(): T
        operator fun component2(): (T) -> Unit
    }
    

    You need to add T type and a lambda that takes T as param and returns unit.

    And inside SnapshotImpl source code of MutableState it's used as

    override operator fun component2(): (T) -> Unit = { value = it }
    

    so anything you set using this lambda is assigned to value T