hi, I was reading about the destructuring declarat...
# getting-started
g
hi, I was reading about the destructuring declarations, and I came across this. can anyone explain please what this means? marked with operator keyword where? i can use component function without marking them with operator
y
You could theoretically have a function called
component1
without it being an
operator fun
, and hence it wouldn't get the spiffy syntax. This applies to all other operators I believe
🙌 1
s
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:
Copy code
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
}
🙌 1
g
thanks for all the answers! i really appreciate it)
@Szymon Jeziorski so i cant use operator in data class? then is there a way to override data class component functions?
e
you can't override them
🙌 1
s
You can use your own operator functions in data classes (ie. get, plus, minus etc), but you cannot override implicitly implemented componentN functions for them
🙌 1
g
okay, got it. thanks a lot!