https://kotlinlang.org logo
#android
Title
# android
b

Benjamin Szilagyi

03/07/2024, 7:32 PM
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

ephemient

03/07/2024, 7:53 PM
that function already exists, it's called
not()
👍 1
b

Benjamin Szilagyi

03/07/2024, 10:12 PM
Yes, but I really don't like that name of that method, dunno why :/
v

vanshg

03/07/2024, 11:46 PM
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

Arun Sudharsan

03/20/2024, 7:21 AM
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