Kotlin component2用法及代码示例

118 阅读1分钟

本文方法及代码示例基于 Kotlin 2.1.20 Released

component2 所在包 kotlin.collections.component2,其相关用法介绍如下:

用法一

operator fun <T> Array<out T>.component2(): T

operator fun ByteArray.component2(): Byte

operator fun ShortArray.component2(): Short

operator fun IntArray.component2(): Int

operator fun LongArray.component2(): Long

operator fun FloatArray.component2(): Float

operator fun DoubleArray.component2(): Double

operator fun BooleanArray.component2(): Boolean

operator fun CharArray.component2(): Char

@ExperimentalUnsignedTypes operator fun UIntArray.component2(): UInt

@ExperimentalUnsignedTypes operator fun ULongArray.component2(): ULong

@ExperimentalUnsignedTypes operator fun UByteArray.component2(): UByte

@ExperimentalUnsignedTypes operator fun UShortArray.component2(): UShort

从数组中返回第二个 element

如果此数组的大小小于 2,则抛出 IndexOutOfBoundsException,除非在 Kotlin/JS 中未指定行为。

用法二

operator fun <T> List<T>.component2(): T

从列表中返回第二个 element

如果此列表的大小小于 2,则抛出 IndexOutOfBoundsException

用法三

operator fun <K, V> Entry<K, V>.component2(): V

返回映射条目的值组件。

此方法允许在使用Map时使用解构声明,例如:

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

相关方法