2

The Kotlin coding conventions, in the section Using infix functions, says:

Declare a function as infix only when it works on two objects which play a similar role. Good examples: and, to, zip. Bad example: add.

Don't declare a method as infix if it mutates the receiver object.

My first question is: in what way is add a bad example?

Then in the discussion of basic types, it explains that the bitwise operators are "named functions that can be called in infix form" and it gives this example (as part of a larger expression):

(1 shl 2)

To me it seems that the three Kotlin shift operations (shl, shr, and ushr) violate the coding conventions. The left and right operands don't play similar roles at all. The left operand is the original bit pattern and the right operand is how far the bit pattern should be shifted.

Am I missing something here?

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521

1 Answers1

5

add (let's choose the add of the MutableList interface) is a bad example because it breaks the rule:

Don't declare a method as infix if it mutates the receiver object.

add mutates the original list and returns a Boolean.


In Kotlin there are no dedicated operators for bitwise operations. So, in order to call them conveniently they created as infix functions.

The integer addition on the other hand has a dedicated operator +. That's why there is no need to make plus (of Int) an infix function, even though it would be a suitable candidate.

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
  • 2
    Ah. I was thinking of `add` as in `plus`, but of course it's usually a mutating method name. I'm still curious why the Kotlin designers chose to use method names for the shift operators and, in violation of their own coding conventions, chose to make them work as infix functions. They could have simply adopted Java's `<<`, `>>`, and `>>>` operator symbols. – Ted Hopp May 05 '19 at 03:24