阅读 316

Kotlin - Pair 和 Triple

Kotlin 标准库提供了 Pair 和 Triple 数据类,分别表示二元组和三元组对象。它们的定义分别如下:

public data class Pair<out A, out B>(
    public val first: A,
    public val second: B
) : Serializable {

    public override fun toString(): String = "($first, $second)"
}

public infix fun <A, B> A.to(that: B): Pair<A, B> = Pair(this, that)

public fun <T> Pair<T, T>.toList(): List<T> = listOf(first, second)


public data class Triple<out A, out B, out C>(
    public val first: A,
    public val second: B,
    public val third: C
) : Serializable {

    public override fun toString(): String = "($first, $second, $third)"
}


public fun <T> Triple<T, T, T>.toList(): List<T> = listOf(first, second, third)

复制代码

我们可以使用 Pair 对象来初始化一个 Map,代码示例如下:

val map = mapOf( 1 to "A", 2 to "B", 3 to "C")
复制代码
文章分类
后端
文章标签