Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Kotlin operator overloading

Kotlin operator overloading

Operator overloading lets custom types also use +、-、[] these symbols, making the code closer to mathematical expressions.

Kotlin implements overloading by adding the operator keyword to a function; essentially it translates the operator into an ordinary function call.


The operator keyword

To overload an operator, define a function with a fixed name and prefix it with operator。

This function can be a class member function or an extension function, but it must be modified with operator ; otherwise compilation fails.

Example

class

Point

(

val x

:

Int, val y

:

Int

)

{

   

// the function must be named plus and modified with operator

    operator fun plus

(

other

:

Point

)

:

Point

=

Point

(

x

other.

x

, y

other.

y

)

    override fun toString

(

)

:

String

=

"($x, $y)"

}

fun main

(

)

{

    val a

=

Point

(

1

,

2

)

    val b

=

Point

(

3

,

4

)

   

// a + b is translated by the compiler into a.plus(b)

    println

(

a

b

)

    println

(

a.

plus

(

b

)

)

}

Running result:



(4, 6)

(4, 6)

Note:Operator overloading is just syntactic sugar. The compiler translates a + b directly into a.plus(b), so what is overloaded is only the notation, not the operator's own precedence.


Full list of overloadable operators

Each operator corresponds to a fixed function name; a wrong name or wrong number of parameters will fail to overload.

Expression translates to Description
+a a.unaryPlus() unary plus
-a a.unaryMinus() unary minus
!a a.not() logical NOT
a++ a = a.inc() increment, requires a to be var
a-- a = a.dec() decrement, requires a to be var
a + b a.plus(b) Addition
a - b a.minus(b) Subtraction
a * b a.times(b) Multiplication
a / b a.div(b) Division
a % b a.rem(b) Remainder
a..b a.rangeTo(b) closed range
a.. a.rangeUntil(b) half-open range, since Kotlin 1.9
a in b b.contains(a) containment check
a[i] a.get(i) indexed read
a[i] = b a.set(i, b) Index assignment
a() a.invoke() calling an object like a function
a == b a?.equals(b) ?: (b === null) structural equality
a != b !(a?.equals(b) ?: (b === null)) structural inequality
a > b a.compareTo(b) > 0 comparison
a < b a.compareTo(b) < 0 comparison
a >= b a.compareTo(b) >= 0 comparison
a <= b a.compareTo(b) <= 0 comparison
a += b a = a.plus(b) or a.plusAssign(b) compound assignment, choose only one of the two
a -= b a = a.minus(b) or a.minusAssign(b) compound assignment
a *= b a = a.times(b) or a.timesAssign(b) compound assignment
a /= b a = a.div(b) or a.divAssign(b) compound assignment
a %= b a = a.rem(b) or a.remAssign(b) compound assignment

The following operators cannot be overloaded:&&、||、===、!==、is、!is、?:、=。


Unary operators and increment/decrement

unary operators correspond to unaryPlus、unaryMinus and not three functions, none of which take parameters.

increment/decrement correspond to inc and dec, which return a new value that the compiler assigns back to the original variable, so the variable must be var.

Example

data

class

Counter

(

val value

:

Int

)

{

   

// -counter

    operator fun unaryMinus

(

)

=

Counter

(

value

)

   

// counter++

    operator fun inc

(

)

=

Counter

(

value

1

)

   

// counter--

    operator fun dec

(

)

=

Counter

(

value

1

)

}

fun main

(

)

{

    val c

=

Counter

(

10

)

    println

(

c

)

   

// ++ and -- reassign the variable, so it must be declared var

    var n

=

Counter

(

0

)

    n

++

    println

(

n

)

    n

--

    println

(

n

)

}

Running result:



Counter(value=-10)

Counter(value=1)

Counter(value=0)

Note:Kotlin does not distinguish prefix from postfix increment/decrement;n++ and ++n both call inc(), and cannot be distinguished by parameters as in C++. They only change the variable itself; the return value does not participate in the operation.


Compound assignment operators

compound assignment a += b has two translation forms, depending on whether the type defines plus or plusAssign。

If both are defined, the compiler cannot decide which to use and reports an error directly.

What is defined Translation of a += b Applicable scenarios
only plus a = a + b immutable type, a must be var
only plusAssign a.plusAssign(b) mutable type, a can be val
both defined compile error must delete one of them

Example

class

Basket

{

   

private

val items

=

mutableListOf

<

String

(

)

// plusAssign returns Unit, modifying the object's own state

   

// so basket declared as val can also use +=

    operator fun plusAssign

(

item

:

String

)

{

        items

+=

item

   

}

    override fun toString

(

)

:

String

=

items.

toString

(

)

}

fun main

(

)

{

    val basket

=

Basket

(

)

    basket

+=

"Apple"

    basket

+=

"Banana"

    basket

+=

"RUNOOB merchandise"

    println

(

basket

)

}

Running result:



[苹果, 香蕉, RUNOOB 周边]


Comparison operators

structural equality is determined by equals , and comparison is determined by compareTo .

equals is already in Any is declared as an operator in ..., so when overriding it you only need to write override, no need to add operator。

Example

data

class

Version

(

val major

:

Int, val minor

:

Int

)

:

Comparable

<

Version

{

// after implementing Comparable, > < >= = can all be used directly

    override fun compareTo

(

other

:

Version

)

:

Int

{

       

if

(

major

!=

other.

major

)

return

major

other.

major

       

return

minor

other.

minor

   

}

}

fun main

(

)

{

    val current

=

Version

(

2

,

2

)

    val old

=

Version

(

1

,

9

)

    println

(

current

old

)

    println

(

current

<

old

)

println

(

current

=

Version

(

2

,

2

)

)

println

(

current

==

Version

(

2

,

2

)

)

println

(

current

!=

old

)

}

Running result:



true

false

true

true

true

Contract:If both the compareTo returns 0,equals should also return true. Violating this convention will make sorted()、TreeSet comparison-dependent APIs like this exhibit hard-to-diagnose problems.


Indexed access and in

bracket reads correspond to get, bracket writes correspond to set,in Corresponds to contains。

All three functions support multiple parameters, so two-dimensional indexing is possible.

Example

class

Playlist

{

   

private

val songs

=

mutableListOf

<

String

(

)

// list[0] -> list.get(0)

    operator fun get

(

index

:

Int

)

:

String

=

songs

[

index

]

   

// list[0] = "x" -> list.set(0, "x")

    operator fun set

(

index

:

Int, value

:

String

)

{

        songs

[

index

]

=

value

   

}

   

// "x" in list -> list.contains("x")

    operator fun contains

(

title

:

String

)

:

Boolean

=

songs.

any

{

it.

contains

(

title

)

}

    operator fun plusAssign

(

song

:

String

)

{

        songs

+=

song

   

}

}

fun main

(

)

{

    val list

=

Playlist

(

)

    list

+=

"Runoob Tutorial"

    list

+=

"Kotlin Getting Started"

    list

+=

"RUNOOB in Practice"

    println

(

list

[

0

]

)

    list

[

1

]

=

"Kotlin Value Classes"

    println

(

list

[

1

]

)

    println

(

"Value Classes"

in list

)

    println

(

"Java"

in list

)

}

Running result:



Runoob 教程

Kotlin 值类

true

false


invoke: calling an object like a function

After defining invoke , the object itself can be called like a function.

together with vararg parameters, and can also let the same object support multiple calling forms.

Example

class

Formatter

(

val prefix

:

String

)

{

   

// f("x") -> f.invoke("x")

    operator fun invoke

(

text

:

String

)

:

String

=

"$prefix$text"

   

// f("x", "y") -> f.invoke("x", "y")

    operator fun invoke

(

vararg texts

:

String

)

:

String

=

        texts.

joinToString

(

", "

)

{

"$prefix$it"

}

}

fun main

(

)

{

    val f

=

Formatter

(

"[RUNOOB] "

)

    println

(

f

(

"First item"

)

)

    println

(

f

(

"First item"

,

"Second item"

,

"Third item"

)

)

}

Running result:



[RUNOOB] 第一条

[RUNOOB] 第一条, [RUNOOB] 第二条, [RUNOOB] 第三条


Practical example: a 2D vector

Vectors are the most natural application for operator overloading; addition, subtraction, scalar multiplication, negation, and accessing components by index all match mathematical intuition.

Example

data

class

Vector

(

val x

:

Double

, val y

:

Double

)

{

    operator fun plus

(

other

:

Vector

)

=

Vector

(

x

other.

x

, y

other.

y

)

    operator fun minus

(

other

:

Vector

)

=

Vector

(

x

other.

x

, y

other.

y

)

   

// Scalar multiplication: vector * scalar

    operator fun times

(

scale

:

Double

)

=

Vector

(

x

scale, y

scale

)

    operator fun unaryMinus

(

)

=

Vector

(

x,

y

)

   

// v[0] gets x, v[1] gets y

    operator fun get

(

index

:

Int

)

:

Double

=

when

(

index

)

{

       

0

->

x

       

1

->

y

       

else

->

throw

IndexOutOfBoundsException

(

"The vector has only two components, indexed by $index"

)

   

}

    override fun toString

(

)

:

String

=

"($x, $y)"

}

fun main

(

)

{

    val a

=

Vector

(

1.0

,

2.0

)

    val b

=

Vector

(

3.0

,

4.0

)

    println

(

a

b

)

    println

(

a

b

)

    println

(

a

2.0

)

    println

(

a

)

    println

(

a

[

0

]

)

    println

(

a

[

1

]

)

}

Running result:



(4.0, 6.0)

(-2.0, -2.0)

(2.0, 4.0)

(-1.0, -2.0)

1.0

2.0


Practical example: money

Money calculations are also well suited to operators, and combined with a value class you also get type safety for free.

The following example stores money as a Long in units of "cents", avoiding the precision problems caused by floating-point numbers.

Example

import

kotlin.math.abs

@JvmInline

value

class

Money

(

val cents

:

Long

)

{

    operator fun plus

(

other

:

Money

)

=

Money

(

cents

other.

cents

)

    operator fun minus

(

other

:

Money

)

=

Money

(

cents

other.

cents

)

   

// Multiply by quantity

    operator fun times

(

quantity

:

Int

)

=

Money

(

cents

quantity

)

    operator fun compareTo

(

other

:

Money

)

:

Int

=

cents.

compareTo

(

other.

cents

)

   

// Output in a money format like 19.99

    override fun toString

(

)

:

String

{

        val sign

=

if

(

cents

<

0

)

"-"

else

""

        val absCents

=

abs

(

cents

)

       

return

"$sign${absCents / 100}.${(absCents % 100).toString().padStart(2, '0')}"

   

}

}

fun main

(

)

{

    val price

=

Money

(

1999

)

           

// 19.99

    val total

=

price

3

Money

(

500

)

 

// 19.99 * 3 + 5.00

    println

(

"Unit price: $price"

)

    println

(

"Total: $total"

)

    println

(

"Total greater than unit price: ${total > price}"

)

    println

(

"Difference: ${total - price}"

)

}

Running result:



单价:19.99

总价:64.97

总价大于单价:true

差额:44.98


Caveats: don't overuse it

Operator overloading improves readability, provided its semantics match the common meaning of the symbol.

If both the + performs deletion,* performs fetching the first element, the code becomes harder to understand than calling a function directly.

Principle Description
Semantics should be intuitive + means combine or add, * means scale or repeat
Don't change your own state plus should return a new object; to modify itself use plusAssign instead
Don't define both plus and plusAssign It makes compound assignment ambiguous
Keep consistent with equals When compareTo returns 0, equals should also be true
Prioritize readability If a function name is clearer than an operator, don't overload
Don't overload just to save characters The benefit of overloading should be expressiveness, not typing a few fewer letters

Common questions

Why equals no need to write operator?

Because equals is already in Any declared as an operator function in , a subclass overriding it only needs to override, writing operator instead causes an error.

Can extension functions overload operators?

Yes, but equals is an exception. It must be overridden in the class, not written as an extension function, because extension functions are resolved statically and cannot take part in polymorphism.

Why a += b reports an ambiguity error?

Because the compiler finds both plus and plusAssign candidates. Keep plus to mean returning a new object, keep plusAssign to mean modifying in place; just choose one of the two.

Why does a custom inc() require a var variable?

Because a++ is translated into a = a.inc(), which is essentially a reassignment; a val variable cannot do this.