How to write in Kotlin:
flags |= newFlag
Only what I have found is:
flags = flags or newFlag
Is there a build-in bitwise or
operator with assignment?
How to write in Kotlin:
flags |= newFlag
Only what I have found is:
flags = flags or newFlag
Is there a build-in bitwise or
operator with assignment?
There is no built in bitwise-or assignment operator in Kotlin (yet).
or
and and
, I would no longer expect them to be added to Kotlin –
Arietta As you wrote yourself this would do the job:
var flag = false
for (i in 1..5) {
flag = flag or someCondition(i, flag)
}
fun someCondition(i: Int, flag: Boolean): Boolean {
println("i: $i, flag: $flag")
return true
}
Outputs:
i: 1, flag: false
i: 2, flag: true
i: 3, flag: true
i: 4, flag: true
i: 5, flag: true
This is because or
does a logical or operation (both expressions are evaluated). Therefore it would also keep flag
to true
even if someCondition()
would return false
at a later iteration.
If its just about making sure a true boolean stays true then this code does the job as well. If you're coming from Java this style might be more easy to understand:
var flag = false
for (i in 1..5) {
flag = someCondition(i, flag) || flag
}
i: 1, flag: false
i: 2, flag: true
i: 3, flag: true
i: 4, flag: true
i: 5, flag: true
However be advised it will lead to unwanted behaviour due to short-circuit evaluation (||
) when chaining more conditions:
var flag = false
for (i in 1..5) {
flag = someCondition(i, flag) || someOtherCondition() || flag
}
fun someCondition(i: Int, flag: Boolean): Boolean {
println("i: $i, flag: $flag")
return true
}
fun someOtherCondition(): Boolean {
println("Nobody calls me :(")
return true
}
Leads to:
i: 1, flag: false
i: 2, flag: true
i: 3, flag: true
i: 4, flag: true
i: 5, flag: true
So it's a good idea to adapt to or
anyways quickly.
© 2022 - 2025 — McMap. All rights reserved.
or=
,and=
. Or highlevel functions such as: addFlags (|=), removeFlags (&= ~), keepFlags (&=) -- or some better names. – Borschref
like in C#? How would you recommend to work with flags in Kotlin? Is it possible to simplify work with flags using some advanced Kotlin features (for instance, equivalent for C# code:someObject.someMember &= ~flags
). – BorschsomeObject.someMember
is from Android SDK.) – Borsch