Kotlin Array - take() Function



The Kotlin array take() function is used to return a list containing first n element of an array. n is the number of elements that should be returned from an array.

Exception

This function throw an exception IllegalArgumentException if n is negative.

Syntax

Following is the syntax of Kotlin array take() function −

fun <T> Array<out T>.take(n: Int): List<T>

Parameters

This function accepts a parameter n, which represents a number that must be smaller or equal to the size of an array.

Return value

This function returns a list.

Example 1

Following is a basic example to demonstrate the use of take() function −

fun main(args: Array<String>){
   var arr = arrayOf(3, 4, 5, 6)
   print("Array elements: ")
   println(arr.joinToString())

   // use take function
   val list = arr.take(3)
   println("list: "+ list)
}

Output

The above code generate following output −

Array elements: 3, 4, 5, 6
list: [3, 4, 5]

Example 2

Let's see another example. Here, we use the take function to return a list containing element of the string array −

fun main(args: Array<String>){
   var arr = arrayOf<String>("Daisy", "Lily", "Rose", "Lotus", "Sunflower")
   print("Array elements: ")
   println(arr.joinToString())

   // use take function
   val list = arr.take(4)
   println("List of flower: "+ list)
}

Output

Following is the output −

Array elements: Daisy, Lily, Rose, Lotus, Sunflower
List of flower: [Daisy, Lily, Rose, Lotus]

Example 3

Let's see what will happen if we pass the -ve value as a parameter of take() function −

fun main(args: Array<String>){
   var arr = arrayOf<Int>(1, 2, 3, 4, 5)
   print("Array elements: ")
   println(arr.joinToString())

   // use take function
   val list = arr.take(-1)
   println("List: "+ list)
}

Output

The above code produce following output if we pass -ve value −

Array elements: 1, 2, 3, 4, 5
Exception in thread "main" java.lang.IllegalArgumentException: Requested element count -1 is less than zero.
kotlin_arrays.htm
Advertisements