[Proposal] Logical augmented assigment operators

@al3c and @jacek.s.gajek But then, you build an intermediate list of boolean values, and it is totally unnecessary. If you really don’t want to introduce a |= operator, the best bet for this particular example would be something like folding :

val changed = items.fold(false) { acc,  item -> add(item) || acc }

But anyway. Any target interoperability platform (Java, JavaScript, C, Objective-C, Swift, etc.) provides such operator. Then, I think it would be “natural” to provide it with Kotlin.

It could be confusing to allow it to be overriden however, so maybe, we could make it a “closed” operator only available for Booleans.
If someone has a good example of how such an operator could be overriden without confusion in interpretation, my opinion on this matter could change, however.

1 Like

What is confusing about it? I think for consistency it should be exactly as plusAssign() and other operators.

|= and &= imply boolean logic. By briefly thinking about it, I have not found any clear examples :

  • In standard objects, I cannot find a good candidate for such overload (Lists, datetimes, numerics, etc.)
  • Let’s say I’ve got a custom data class Person, or whatever simple common example, I cannot find a good use of “orAssign” or “andAssign” operator.

But as I said, if someone can provide a good example, my opinion could change.

I’m also a little afraid of them being used to create overloads with a nullability purpose, like : personA |= personB would mean “replace all null properties in person A with value from propertyB”.

I think it implies boolean-like logic the same way how e.g. /= or *= implies number-like logic.

I don’t understand why you look for examples like Person which doesn’t sound like something that could be ORed or ANDed. I doubt you would provide Person as an example for /=, you would probably provide something that is somehow conceptually dividable. It is the same for |=, &=:

  • Custom boolean wrappers - sometimes we may have to do this for some reason
    • Boolean value with additional metadata.
    • Observable/bindable/reactive boolean, e.g. something like MutableStateFlow<Boolean>.
  • Domain objects that represent a boolean value, but have a special domain meaning, e.g. something like Flag, Signal in electronic circuits, etc.
  • Tuples of booleans or other fixed-size containers of booleans, e.g. ORing two matrices of booleans of the same size.
  • Other examples where some complex object represents a boolean:
    • Framework for constructing different kind of expressions and they could be of a boolean type. There are many examples of such frameworks, most notably ORMs do this for WHERE clauses.
2 Likes

I vote for ||=, &&= will be very convenient