takeWhile所在位置是kotlin.collections.takeWhile,其相关用法介绍如下。

用法:

inline fun <T> Array<out T>.takeWhile(
    predicate: (T) -> Boolean
): List<T>
inline fun ByteArray.takeWhile(
    predicate: (Byte) -> Boolean
): List<Byte>
inline fun ShortArray.takeWhile(
    predicate: (Short) -> Boolean
): List<Short>
inline fun IntArray.takeWhile(
    predicate: (Int) -> Boolean
): List<Int>
inline fun LongArray.takeWhile(
    predicate: (Long) -> Boolean
): List<Long>
inline fun FloatArray.takeWhile(
    predicate: (Float) -> Boolean
): List<Float>
inline fun DoubleArray.takeWhile(
    predicate: (Double) -> Boolean
): List<Double>
inline fun BooleanArray.takeWhile(
    predicate: (Boolean) -> Boolean
): List<Boolean>
inline fun CharArray.takeWhile(
    predicate: (Char) -> Boolean
): List<Char>
inline fun <T> Iterable<T>.takeWhile(
    predicate: (T) -> Boolean
): List<T>
@ExperimentalUnsignedTypes inline fun UIntArray.takeWhile(
    predicate: (UInt) -> Boolean
): List<UInt>
@ExperimentalUnsignedTypes inline fun ULongArray.takeWhile(
    predicate: (ULong) -> Boolean
): List<ULong>
@ExperimentalUnsignedTypes inline fun UByteArray.takeWhile(
    predicate: (UByte) -> Boolean
): List<UByte>
@ExperimentalUnsignedTypes inline fun UShortArray.takeWhile(
    predicate: (UShort) -> Boolean
): List<UShort>

返回包含满足给定 predicate 的第一个元素的列表。

例子:

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val chars = ('a'..'z').toList()
println(chars.take(3)) // [a, b, c]
println(chars.takeWhile { it < 'f' }) // [a, b, c, d, e]
println(chars.takeLast(2)) // [y, z]
println(chars.takeLastWhile { it > 'w' }) // [x, y, z]
//sampleEnd
}

输出:

[a, b, c]
[a, b, c, d, e]
[y, z]
[x, y, z]