Kotlin Array - randomOrNull() Function



The Kotlin array randomOrNull() function is used to return the random element from this array. Otherwise; null if an array is empty.

If we refresh the code after the first execution, the random element will be changed with every subsequent execution.

Syntax

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

fun <T> Array<out T>.randomOrNull(): T

Parameters

This function does not accepts any parameters

Return value

This function returns a random element. Otherwise; null

Example 1

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

fun main(args: Array<String>) {
   var array = arrayOf<Int>(1, 2, 3, 4, 5, 6, 7, 8)
      
   val ran_num = array.randomOrNull()
   
   println("random number: $ran_num")
}

Output

The above code produce following output −

random number: 1

Example 2

Now, let's create another example. Here, We use the randomOrNull() to check return value if an array is empty −

fun main(args: Array<String>) {
   var array = arrayOf<String>()
      
   val ran_num = array.randomOrNull()
   
   println("random number: $ran_num")
}

Output

Following is the output −

random number: null

Example 3

The below example, creates an array of type any and returns the random element −

fun main(args: Array<String>) {
   var array = arrayOf<Any>("tutorialspoint", 1, 2, 3, "India")
      
   val ran_value = array.randomOrNull()
   
   println("random value: $ran_value")
}

Output

Following is the output −

random value: India
kotlin_arrays.htm
Advertisements