Gamar Mustafa
02/22/2024, 12:23 PMYoussef Shoaib [MOD]
02/22/2024, 12:30 PMcomponent1
without it being an operator fun
, and hence it wouldn't get the spiffy syntax. This applies to all other operators I believeSzymon Jeziorski
02/22/2024, 12:32 PMoperator
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
}
Gamar Mustafa
02/22/2024, 12:40 PMGamar Mustafa
02/22/2024, 12:40 PMephemient
02/22/2024, 12:52 PMSzymon Jeziorski
02/22/2024, 12:56 PMGamar Mustafa
02/22/2024, 1:01 PM