aaverin
08/13/2019, 9:35 AMinterface Parent {
val a: String
val b: String
}
data class Person1(
override val a: String = "Person1 a",
override val b: String = "Person1 b"
): Parent
data class Person2(
override val b: String = "Person2 b",
override val a: String = "Person2 a"
): Parent
fun main() {
val person1 = Person1()
val person2 = Person2()
person1.let {
val (a, b) = person1
println("Destructuing person1, a is ${a}, b is ${b}")
}
person2.let {
val (a, b) = person2
println("Destructuing person2, a is ${a}, b is ${b}")
}
}
Results in
Destructuing person1, a is Person1 a, b is Person1 b
Destructuing person2, a is Person2 b, b is Person2 a
https://pl.kotl.in/sUDuggWbxaaverin
08/13/2019, 9:36 AMaaverin
08/13/2019, 9:46 AMmodule.exports.batch = payload => {
return <http://client.post|client.post>('/batch', payload)
}
const { batch: batchApi } = require('myApi')
You can destructure any property and also change it’s name, and it’s not tied to the index of the property, at least not explicetelyDico
08/13/2019, 9:52 AMstreetsofboston
08/13/2019, 9:52 AMcomponentXXX
methods/extension-functions on the interface.
Destructuring is fragile, as your example shows. There are other situations as well that expose its fragility. Write unit-tests to test your code.Dico
08/13/2019, 10:25 AMDico
08/13/2019, 10:26 AMaaverin
08/13/2019, 10:44 AMbatch
is property that I get from another object, and batchApi
is my new local variable name that I will be using in this particular moduleaaverin
08/13/2019, 10:45 AMaaverin
08/13/2019, 10:48 AMstreetsofboston
08/13/2019, 10:50 AMDico
08/13/2019, 12:00 PMkarelpeeters
08/13/2019, 12:07 PM(x, y) = point
for example.poohbar
08/13/2019, 1:39 PMkarelpeeters
08/13/2019, 1:57 PMpoohbar
08/13/2019, 2:01 PMkarelpeeters
08/13/2019, 2:06 PMval x = point.x
poohbar
08/13/2019, 2:16 PMJoffrey
08/14/2019, 7:03 AMPair
, or even custom generic types like:
data class ParseResult<T>(
val data: T,
val stats: Stats,
)
fun parseLogs(file: File): ParseResult<List<Log>> = //...
val (logs, logParsingStats) = parseLogs(logFile)
Having to name the logs data
here would be a downside of name-based destructuring.
I usually don't use destructuring that much, though, I have to admit 🙂