中缀调用和解构声明

Quibbler 2020-11-4 75

中缀调用和解构声明


        介绍一个Kotlin中和Pair键值对相关的简洁语法糖,引申出中缀调用和解构声明。学习Kotlin似乎看到Python的身影。



1、Pair

        Pair键值对是Kotlin标准库中的类,它的对象包含两个值:keyvalue。关于两个键值对的比较:如果键值对中的这两个值相等,那么键值对相等。

/**
 * Represents a generic pair of two values.
 *
 * There is no meaning attached to values in this class, it can be used for any purpose.
 * Pair exhibits value semantics, i.e. two pairs are equal if both components are equal.
 *
 * @param A type of the first value.
 * @param B type of the second value.
 * @property first First value.
 * @property second Second value.
 * @constructor Creates a new instance of Pair.
 */
public data class Pair<out A, out B>(
    public val first: A,
    public val second: B
)

        


2、中缀调用

        使用mapOf()函数来快速创建Map集合的时候,见过如下的语法,刚接触Kotlin会有点懵:

    val datas = mapOf(1 to 'a', 2 to 'b', 3 to 'c', 4 to 'd')


2.1、infix中缀调用

        前面提到的to其实是中缀调用:一种特殊的函数调用。Pair类中定义了一个to中缀调用函数,定义函数的时候用infix标记该函数,表示允许以中缀符号的方式来调用该函数。

/**
 * Creates a tuple of type [Pair] from this and [that].
 *
 * This can be useful for creating [Map] literals with less noise, for example:
 * @sample samples.collections.Maps.Instantiation.mapFromPairs
 */
public infix fun <A, B> A.to(that: B): Pair<A, B> = Pair(this, that)


2.2、使用中缀调用

        有两种调用方式,一种是直观的to()函数调用,

    val p: Pair<Int, Int> = 1.to(2)

        另一种是函数名放在目标名称和参数之间。

    val p: Pair<Int, Int> = 1 to 2



3、解构声明

        继续使用Pair类,借助Pair对象可以快速的定义两个值,将其中的键值对提取出来:

    val p: Pair<Int, Int> = 1 to 2
    val (key, value) = p
    
    //或者
    var (key, value) = 1 to 2

        在学习Kotlin循环语句的时候有见过这样的解构声明语法,提取索引index和元素element,详见Kotlin循环语句

    val list = arrayOf(1, 2, 3, 4)
    
    for ((index, element) in list.withIndex()) {
        println("index = $index , element =$element;")
    }



不忘初心的阿甘
最新回复 (0)
    • 安卓笔记本
      2
        登录 注册 QQ
返回
仅供学习交流,切勿用于商业用途。如有错误欢迎指出:fluent0418@gmail.com