https://kotlinlang.org logo
#language-evolution
Title
# language-evolution
y

Youssef Shoaib [MOD]

02/22/2024, 12:41 PM
Is there a pre-existing proposal for an
operator fun componentN(i: Int)
that would generalise
component1
,
component2
etc? Or perhaps
get
should serve that purpose if it has one
Int
argument
k

Klitos Kyriacou

02/22/2024, 1:53 PM
I wonder how difficult it would be to write a compiler plugin that would allow you to do something like:
Copy code
@Destructurable
MyClass {
    fun component(index: Int) = TODO() // generates componentN() functions for 1-based index
    operator fun get(index: Int) = TODO() // generates componentN() functions for 0-based index if fun component() is not defined
}
It would of course be temporary, pending resolution of the above issue.
e

ephemient

02/22/2024, 2:00 PM
if Kotlin had typeclasses or structural types,
Copy code
typeclass Indexed<E> {
    operator fun get(index: Int): E]
}
operator fun <E> Indexed<E>.component1(): E = get(0)
operator fun <E> Indexed<E>.component2(): E = get(1)
// etc.
would "just work" for existing types. I don't think it'll happen though