Hi guys, it is not clear for me which channel shou...
# android
b
Hi guys, it is not clear for me which channel should I share that thing but, I really love the Bool.toggle() in Swift , it was easy to create a similar one 😁
e
that function already exists, it's called
not()
👍 1
b
Yes, but I really don't like that name of that method, dunno why :/
v
toggle implies a stateful action though. which what you have written is not
1
toggle in Swift is a
mutating func
. afaik this is not achievable in kotlin
a
In Kotlin, you can't directly change the state of a
Boolean
within an extension function because it's a value type and is passed by value, not by reference. However, you can achieve a similar effect by using a wrapper class that holds the Boolean value. Here's how you can do it:
Copy code
class MutableBoolean(var value: Boolean)

fun MutableBoolean.toggle(): Boolean {
    this.value = !this.value
    return this.value
}
You can use this
toggle
function like this:
Copy code
val myBool = MutableBoolean(true)
println(myBool.toggle()) // prints: false
println(myBool.toggle()) // prints: true
❤️ 1
👍 1