Hi! In java, there is a shortcut for switching the...
# getting-started
o
Hi! In java, there is a shortcut for switching the value of a boolean, like this:
myBoolean ^= true
So if it was true, it becomes false and if it was false it becomes true. Is there an equivalent in kotlin?
k
Nothing shorter than
myBoolean = !myBoolean
๐Ÿ‘Œ 1
๐Ÿ‘ 5
d
Shorter and also way more expressive of your actual intent.
โž• 2
๐Ÿ‘Œ 3
xor-ing with
true
is clever, but you shouldn't have to look at something as simple as flipping a boolean and have to think about it for a minute.
๐Ÿ‘Œ 1
๐Ÿ‘ 3
o
Oh actually there was a xor() method in kotlin, my bad.. Thanks for responses.. In my case, it is:
viewModel.isChildFragVisible = !viewModel.isChildFragVisible
and I type this in six places, so I thought there might be a better way. But you're right, xor is not very expressive of the intent. May be I can just write a simple extension function called flip() or flipTruth()
k
Not really, because functions can't get things by reference. Something like
viewModel.toggleVisibility()
could work of course.
โž• 4
๐Ÿ‘Œ 1
o
Yeah, sure, that can work as well. Thanks a lot for suggestions!
m
Just to mention that there is not() negation function as well: myBoolean = myBoolean.not() (which is ekvivalent to myBoolean = !myBoolean)