Kotlin Array - none() Function



The Kotlin array none() function checks whether the array or collection contains a specified element. It returns true if no elements match the given predicate, and false if any element matches the predicate.

Syntax

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

fun <T> Array<out T>.none(
   predicate: (T) -> Boolean
): Boolean

Parameters

This function accepts predicate as a parameter.

Return value

This function returns a boolean value.

Example 1

The following is a basic example to demonstrate the use none() function −

fun main(args: Array<String>) {
   var array = arrayOf<Int>(1, 2, 3, 4)
   val elem = array.none({ it%5 == 0 })
   println("$elem")
}

Output

Following is the output −

true

Example 2

Now, let's create another example. Here, we have an array that match the specified predicate −

fun main(args: Array<String>) {
   var array = arrayOf<Int>(1, 2, 3, 4)
   val elem = array.none({ it%2 == 0 })
   println("$elem")
}

Output

The above code returns false if the predicate matched with any element −

false

Example 3

The below example uses the none function to return boolean value, If true if statement will run, Otherwise; else statement −

fun main(args: Array<String>) {
   var array = arrayOf<String>("Hello", "tutorialspoint", "India", "Pvt", "ltd")
   val length = array.none({it.length>5});
    
   if(!length){
      println("Array contains elements have length more than 5 ")
   }   
   else{
      println("Array doesn't contains elements have length more than 5 ")
   }
}

Output

Following is the output −

Array contains elements have length more than 5
kotlin_arrays.htm
Advertisements