https://kotlinlang.org logo
#getting-started
Title
# getting-started
g

Gamar Mustafa

02/22/2024, 12:23 PM
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

Youssef Shoaib [MOD]

02/22/2024, 12:30 PM
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

Szymon Jeziorski

02/22/2024, 12:32 PM
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

Gamar Mustafa

02/22/2024, 12:40 PM
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

ephemient

02/22/2024, 12:52 PM
you can't override them
🙌 1
s

Szymon Jeziorski

02/22/2024, 12:56 PM
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

Gamar Mustafa

02/22/2024, 1:01 PM
okay, got it. thanks a lot!