Destructuring Declarations in Kotlin - Cleverson Zanon | cleverson.ssantos1008@gmail.com (#2318)
* Different Types of Bean Injection in Spring code * Dataclasses in Kotlin * Revert "Different Types of Bean Injection in Spring code" This reverts commit 4b747726b93a9f6bf76d6518792fc77e0d5c2fc9. * Destructuring Declarations in Kotlin * Corrections on Destructuring Declarations in Kotlin
This commit is contained in:
parent
9b143b820c
commit
7f22e3dc35
|
@ -1,11 +1,10 @@
|
|||
package com.baeldung.destructuringdeclarations
|
||||
|
||||
import com.baeldung.destructuringdeclarations.Person
|
||||
import com.baeldung.destructuringdeclarations.Result
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
|
||||
//2.1. Objects
|
||||
//2.1. Objects
|
||||
val person = Person(1, "Jon Snow", 20)
|
||||
val(id, name, age) = person
|
||||
|
||||
|
@ -13,20 +12,15 @@ fun main(args: Array<String>) {
|
|||
println(name) //Jon Snow
|
||||
println(age) //20
|
||||
|
||||
//The equivalent of line 10
|
||||
/* val id = person.component1();
|
||||
val name = person.component2();
|
||||
val age = person.component3();*/
|
||||
|
||||
//2.2. Functions
|
||||
fun getPersonInfo() = Person(2, "Ned Stark", 45)
|
||||
val(idf, namef, agef) = getPersonInfo()
|
||||
|
||||
fun twoValuesReturn(): Result {
|
||||
fun twoValuesReturn(): Pair<Int, String> {
|
||||
|
||||
// needed code
|
||||
|
||||
return Result(1, "success")
|
||||
return Pair(1, "success")
|
||||
}
|
||||
|
||||
// Now, to use this function:
|
||||
|
@ -41,15 +35,10 @@ fun main(args: Array<String>) {
|
|||
}
|
||||
|
||||
//2.4. Underscore and Destructuring in Lambdas
|
||||
val (_, status2) = twoValuesReturn()
|
||||
val (_, name2, age2) = person
|
||||
val (id3, name3) = person
|
||||
|
||||
map.mapValues { entry -> "${entry.value}!" }
|
||||
map.mapValues { (key, value) -> "$value!" }
|
||||
|
||||
//A pair of parameters vs. a destructuring pair
|
||||
/* { a -> ... } // one parameter
|
||||
{ a, b -> ... } // two parameters
|
||||
{ (a, b) -> ... } // a destructured pair
|
||||
{ (a, b), c -> ... } // a destructured pair and another parameter*/
|
||||
|
||||
}
|
Loading…
Reference in New Issue