中缀调用和解构声明

QuibblerQuibbler 2020-11-04 约 5 分钟 1152 次阅读

中缀调用和解构声明

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

1、Pair

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

/**
 * 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;")
    }

相关推荐

Parcelize:Parcelable 实现生成器
Kotlin

Parcelize:Parcelable 实现生成器

Parcelize:Parcelable 实现生成器Parcelable是安卓开发中常用的序列化方式,之前分享过一个Parcelable序列化插件,方便开发者快速生成代码,提高开发效率。1、Parcelize插件Kotlin官方也推出一个Parcelable自动生成的Gradle插件:Parcelize。1.1、引入插件在项目的build.gradle中添加:id("kotlin-parceliz

2.6k
Kotlin的继承
Kotlin

Kotlin的继承

Kotlin的继承1、超类:Any类似于Java中的Object类,Kotlin也有一个叫Any的超类,是所有类的父类,所有类都默认继承自该类。超类的定义如下,其中定义了三个函数:2、open注意上面的Any类用open修饰,表示该类可以被继承。Kotlin中的类默认都是final的,无法被继承:如果想让类可以被继承,就需要用在定义类的地方用open关键字标识该类可以被继承。3、构造器继承中涉及到

2.1k
 Kotlin基本语法
Kotlin

Kotlin基本语法

Kotlin基本语法了解Kotlin语言的基本语法。1、包kotlin文件以.kt结尾,编译文件还是如此只不过在文件名后面加上Kt后缀。这一点和Java不同,Java源文件.java,编译后为.class文件。1.1、包定义每个kotlin文件的第一行就用关键字package定义该文件所在的包。例:1.2、导包用到其它kotlin文件需要使用关键字import导入,这一点和Java一样。kotli

2.1k