operator
functions in Kotlin are functions with special meaning. You can use operator functions to allow special behaviour which underneaths calls those functions. For example, when you use
+
sign on two lists to get new list containing all contents from both input lists,
operator fun <T> Collection<T>.plus
is called underneath.
operator componentN
functions can be used for destructuring classes.
Consider following example:
class Foo(
val firstProp: String,
val secondProp: Int
) {
operator fun component1() = firstProp
operator fun component2() = secondProp
operator fun component3() = "$firstProp$secondProp"
}
class Bar(
val firstProp: String,
val secondProp: Int
) {
fun component1() = firstProp
fun component2() = secondProp
fun component3() = "$firstProp$secondProp"
}
fun main() {
val foo = Foo("one", 1)
val (firstFooProp, secondFooProp, fooComponent3) = foo // destructuring via calling componentN functions implicitly
val bar = Bar("two", 2)
val (firstBarProp, secondBarProp, barComponent3) = bar // compilation error, implicit destructuring not possible due to lack of operator component functions
}