美文网首页
Kotlin- 解构声明(Destructuring Decla

Kotlin- 解构声明(Destructuring Decla

作者: galaxy_zheng | 来源:发表于2019-11-17 18:43 被阅读0次

    (翻译)

    解构声明

    解构声明是Kotlin中另一个重要的特性。我们可以利用这个特性来编写更好的应用程序。

    解构声明是什么?

    解构声明是一种从存储在(可能是嵌套的)对象和数组中的数据中提取多个值的方便方法。它可以用于接收数据的位置(例如赋值的左侧)。

    有时将一个对象分解成多个变量是很方便的,例如:

    val (name, age) = developer
    

    Now, we can use name and age independently like below:

    println(name)
    println(age)
    

    用例中,我们可以使用销毁功能:

    • 从一个函数返回两个值

    Example

    data class Developer(val name: String, val age: Int)
    fun getDeveloper(): Developer {
     // some logic
     return Developer(name, age)
    }
    
    
    // Now, to use this function:
    val (name, age) = getDeveloper()
    
    • 解构声明 和 Maps

    Example

    for ((key, value) in map) {
     // do something with the key and the value
    }
    

    因此,在需要时使用这个结构声明功能。


    (原文)

    Learn Kotlin- Destructuring Declarations

    Destructuring Declarations

    Destructuring Declarations is yet another important feature available in Kotlin. We can take advantage of this feature to write the better application.

    What is Destructuring?

    Destructuring is a convenient way of extracting multiple values from data stored in (possibly nested) objects and Arrays. It can be used in locations that receive data (such as the left-hand side of an assignment).

    Sometimes it is convenient to destructure an object into a number of variables, for example:

    val (name, age) = developer
    

    Now, we can use name and age independently like below:

    println(name)
    println(age)
    

    Use-cases where we can use the Destructuring feature:

    • Returning Two Values from a Function

    Example

    data class Developer(val name: String, val age: Int)
    fun getDeveloper(): Developer {
     // some logic
     return Developer(name, age)
    }
    
    
    // Now, to use this function:
    val (name, age) = getDeveloper()
    
    • Destructuring Declarations and Maps

    Example

    for ((key, value) in map) {
     // do something with the key and the value
    }
    

    So use this Destructuring feature, when it is required.


    原文链接:https://blog.mindorks.com/learn-kotlin-destructuring-declarations
    推荐阅读 结构声明:https://www.jianshu.com/p/f033158857d4

    相关文章

      网友评论

          本文标题:Kotlin- 解构声明(Destructuring Decla

          本文链接:https://www.haomeiwen.com/subject/jltmictx.html