Operator overloading
Operator overloading is a form of polymorphism. Some operators change behaviors on different types. The classic example is the operator plus (+
). On numeric values, plus is a sum operation and on String
is a concatenation. Operator overloading is a useful tool to provide your API with a natural surface. Let's say that we're writing a Time
and Date
library; it'll be natural to have the plus and minus operators defined on time units.
Kotlin lets you define the behavior of operators on your own or existing types with functions, normal or extension, marked with the operator
modifier:
class Wolf(val name:String) { operator fun plus(wolf: Wolf) = Pack(mapOf(name to this, wolf.name to wolf)) } class Pack(val members:Map<String, Wolf>) fun main(args: Array<String>) { val talbot = Wolf("Talbot") val northPack: Pack = talbot + Wolf("Big Bertha") // talbot.plus(Wolf("...")) }
The operator function plus returns a Pack
value. To invoke it, you can use the infix...