Kotlin
Destructuring Declarations
Swift
|
val (name, age) = person
|
let (name, age) = person
|
println(name)
println(age)
|
print(name)
print(age)
|
val name = person.component1()
val age = person.component2()
|
let name = person.component1()
let age = person.component2()
|
for ((a, b) in collection) { ... }
|
for ((a, b) in collection) { ... }
|
Example: Returning Two Values from a Function
|
data class Result(val result: Int, val status: Status)
fun function(...): Result {
// computations
return Result(result, status)
}
// Now, to use this function:
val (result, status) = function(...)
|
data class Result(let result: Int, let status: Status)
func function(...): Result {
// computations
return Result(result, status)
}
// Now, to use this function:
let (result, status) = function(...)
|
Example: Destructuring Declarations and Maps
|
for ((key, value) in map) {
// do something with the key and the value
}
|
for ((key, value) in map) {
// do something with the key and the value
}
|
operator fun <K, V> Map<K, V>.iterator(): Iterator<Map.Entry<K, V>> = entrySet().iterator()
operator fun <K, V> Map.Entry<K, V>.component1() = getKey()
operator fun <K, V> Map.Entry<K, V>.component2() = getValue()
|
operator func <K, V> Map<K, V>.iterator(): Iterator<Map.Entry<K, V>> = entrySet().iterator()
operator func <K, V> Map.Entry<K, V>.component1() = getKey()
operator func <K, V> Map.Entry<K, V>.component2() = getValue()
|
Underscore for unused variables (since 1.1)
|
val (_, status) = getResult()
|
let (_, status) = getResult()
|
Destructuring in Lambdas (since 1.1)
|
map.mapValues { entry -> "${entry.value}!" }
map.mapValues { (key, value) -> "$value!" }
|
map.mapValues { entry -> "${entry.value}!" }
map.mapValues { (key, value) -> "$value!" }
|
{ a -> ... } // one parameter
{ a, b -> ... } // two parameters
{ (a, b) -> ... } // a destructured pair
{ (a, b), c -> ... } // a destructured pair and another parameter
|
{ a -> ... } // one parameter
{ a, b -> ... } // two parameters
{ (a, b) -> ... } // a destructured pair
{ (a, b), c -> ... } // a destructured pair and another parameter
|
map.mapValues { (_, value) -> "$value!" }
|
map.mapValues { (_, value) -> "$value!" }
|
map.mapValues { (_, value): Map.Entry<Int, String> -> "$value!" }
map.mapValues { (_, value: String) -> "$value!" }
|
map.mapValues { (_, value): Map.Entry<Int, String> -> "$value!" }
map.mapValues { (_, value: String) -> "$value!" }
|