W3cubDocs

/Kotlin

take

Platform and version requirements: JVM (1.0), JS (1.0), Native (1.0)
fun <T> Array<out T>.take(n: Int): List<T>
fun ByteArray.take(n: Int): List<Byte>
fun ShortArray.take(n: Int): List<Short>
fun IntArray.take(n: Int): List<Int>
fun LongArray.take(n: Int): List<Long>
fun FloatArray.take(n: Int): List<Float>
fun DoubleArray.take(n: Int): List<Double>
fun BooleanArray.take(n: Int): List<Boolean>
fun CharArray.take(n: Int): List<Char>
fun <T> Iterable<T>.take(n: Int): List<T>
@ExperimentalUnsignedTypes fun UIntArray.take(
    n: Int
): List<UInt>
@ExperimentalUnsignedTypes fun ULongArray.take(
    n: Int
): List<ULong>
@ExperimentalUnsignedTypes fun UByteArray.take(
    n: Int
): List<UByte>
@ExperimentalUnsignedTypes fun UShortArray.take(
    n: Int
): List<UShort>

Returns a list containing first n elements.

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
}

Exceptions

IllegalArgumentException - if n is negative.

© 2010–2020 JetBrains s.r.o. and Kotlin Programming Language contributors
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/take.html