Hello everyone ! I'm still trying to learn Jet...
# compose-desktop
l
Hello everyone ! I'm still trying to learn Jetpack Compose (Multiplatform in this case but I don't think it matters ?) and there is something I cannot seem to find online. Let's say I have a component (a Composable Function) with a state written like so :
Copy code
val (counter, setCounter) = remember { mutableStateOf(0) }
If I want to create a
incrementCounter()
function to prevent writing
setCounter(counter + 1)
each time, inside my component I can write :
Copy code
fun incrementCounter(value = 1) { setCounter(counter + value) }
But doing so, Jetpack Compose will behave weirdly and won't update the counter each time. If I instead declare it like that :
Copy code
val incrementCounter = fun(value: Int) { setCounter(counter + value) }
It work without any problem ! The only problem is that I cannot use default values with this syntax. It reminds me of the arrow function in javascript and the reference of
this
. After a lot of trial and error, it seems the destructuration of the mutableState return is the culprit. Does anybody have an idea ? Is it possible to write an internal function in a Jetpack Compose component while still using destructuration ?
t
Not sure if this helps but you could also use following definition:
Copy code
var counter by remember { mutableStateOf(0) }
Than you can use the variable counter like a normal variable. E.g.: counter++ ; counter = 4; ...
1
g
So you do create a local function inside compose function? Could you show some sample code, I'm asking because this is invalid code, it shouldn't be possible to compile fun incrementCounter(value = 1)
l
Thank you Timo, I didn't know that, I'll try as soon as possible ! Andrey, of course I'll share an example with you. But why shouldn't it be possible ? Aren't functions inside functions allowed in Kotlin ?
g
No, I meant that there was no type declaration, so this particular line will not compile So if you show full example it would be helpful. It looks as some issue with closure of values, hit hard to tell exactly
l
Oh okay, to be honest I typed this code with my phone while away from my laptop so I compiled it in my head 😅
Timo, I tried and it worked perfectly thank you I'm so happy 😁 Any idea why the destructuring didn't work though ?
t
No sorry do not use this method. I know that it is in the samples but in my opinion it is better to just use the mutableState directly. Than you have to write counter.value++ or you use the delegate method.