kotlinkotlin-js

Destructuring props passed to functional component in kotlin


In JavaScript, the destructuring of an object is something common.

const foo = {
    a: 1
    b: 2
    c: 3 
};

const {a, b, c } = foo;
console.log(a)

1

Is something like this possigle with KotlinJS React?

interface FooProps : Props {
    var a: Int
    var b: Int
    var c: Int
}

val Foo = FC<FooProps> { props -> 
    val(a, b, c) = props
    ...
}

This is not working. It gives me

Destructuring declaration initializer of type FooProps must have a 'component1()' function


Solution

  • Kotlin supports destructuring declarations, however they work in a different way than JavaScript. In particular, you can destructure an object like this:

    val (property1, property2, property3, ..., propertyN) = object
    

    assuming that object contains certain methods:

    Example:

    class Person(val name: String, val dateOfBirth: LocalDate) {
        operator fun component1(): String = name
        operator fun component2(): LocalDate = dateOfBirth
    }
    
    val johnDoe = Person("John", LocalDate.of(1980, JANUARY, 1))
    
    val (name, dob) = johnDoe
    println("$name -> $dob") // prints John -> 1980-01-01
    

    Use can make use of extension functions to implement this behaviour on classes you don't own. Example:

    operator fun String.component1(): Int = this.length
    operator fun String.component2(): Char = this.first()
    
    val someString = "Hello, world"
    
    val (length, firstChar) = someString
    println("$length -> $firstChar") // prints 12 -> H