Binary operators

Binary operators receive a parameter (there are exceptions to this rule—invoke and indexed access).

The Pack.plus extension function receives a Wolf parameter and returns a new Pack. Note that MutableMap also has a plus (+) operator:

operator fun Pack.plus(wolf: Wolf) = Pack(this.members.toMutableMap() + (wolf.name to wolf))

val biggerPack = northPack + Wolf("Bad Wolf")

The following table will show you all the possible binary operators that can be overloaded:

Operator

Equivalent Notes
x + y x.plus(y)
x - y x.minus(y)
x * y x.times(y)
x / y x.div(y)
x % y x.rem(y)

From Kotlin 1.1, previously mod.

x..y x.rangeTo(y)
x in y y.contains(x)
x !in y !y.contains(x)
x += y x.plussAssign(y) Must return Unit.
x -= y x.minusAssign(y) Must return Unit.
x *= y x.timesAssign(y) Must return Unit.
x /= y x.divAssign(y) Must return Unit.
x %= y x.remAssign(y) From Kotlin 1.1, previously modAssign. Must return Unit.
x == y x?.equals(y) ?: (y === null) Checks for null.
x != y !(x?.equals(y) ?: (y === null)) Checks for null.
x < y x.compareTo(y) < 0 Must return Int.
x > y x.compareTo(y) > 0 Must return Int.
x <= y x.compareTo(y) <= 0 Must return Int.
x >= y x.compareTo(y) >= 0 Must return Int.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.76.138