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
}
Klitos Kyriacou
02/22/2024, 1:53 PM
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