Kotlin Array - takeLastWhile() Function



The Kotlin array takeLastWhile() function is used to return a list containing last element of an array satisfying the specified predicate.

Here, the last elements represent the result of applying the predicate to each element from the last of an array and stored in a new list.

Syntax

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

inline fun <T> Array<out T>.takeLastWhile(
   predicate: (T) -> Boolean
): List<T>

Parameters

This function accepts predicate as a parameter.

Return value

This function returns a list containing last n element that satisfies the predicate.

Example 1

Following is a basic example to demonstrate the use of takeLastWhile() function to return a list containing last elements greater than specified predicate −

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

   // use takeLastWhile function
   val list = arr.takeLastWhile({it>=5})
   println("list having element greater than 5: "+ list)
}

Output

The above code generate following output −

Array elements: 3, 4, 5, 6
list having element greater than 5: [5, 6]

Example 2

Let's see another example. Here, we use the takeLastWhile function to return a list containing last elements having length greater than 5 −

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

   // use takeLastWhile function
   val list = arr.takeLastWhile({it.length>5})
   println("last n flower having length greater than 5 is: ")
   println("list:" + list)
}

Output

Following is the output −

Array elements: Lily, Rose, Daisy, Lotus, Sunflower
last n flower having length greater than 5 is: 
list:[Sunflower]

Example 3

Following is another scenario: let's see what happens if last element does not satisfy the given predicate −

data class Product(val name: String, val price: Double)
fun main(args: Array<String>) {
   val products = arrayOf(
      Product("Laptop", 999.99),
      Product("Mouse", 19.99),
      Product("Keyboard", 49.99),
      Product("Monitor", 199.99)
   )
   // use takeLast function
   val list = products.takeLastWhile{it.price>200}

   // Display the result
   println("Product and Price List: $list")
}

Output

The above code produce empty list if last element does not satisfies the predicate −

Product and Price List: []
kotlin_arrays.htm
Advertisements