Kotlin Array - random() Function



The Kotlin array random() function is used to return the random element from this array.

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

Exceptions

This function throw an exception "NoSuchElementException" if this array is empty.

Syntax

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

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

Parameters

This function does not accepts any parameters

Return value

This function returns a value that is a randomly selected element from the array.

Example 1

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

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

Output

The above code produce following output −

random number: 6

Example 2

Now, let's create another example. Here, We use the random() to generate 4 digit random number −

fun main(){
   var randomNum =  (1000..9999).random();

   //generating the random code.
   println("Random code: $randomNum")
}

Output

Following is the output −

Random code: 7736

Example 3

The below example, generates a 16 digit random String, using the random() and joinToString() function −

fun randomID(): String = List(16) {
   (('a'..'z') + ('A'..'Z') + ('0'..'9')).random()
}.joinToString("")
fun main(args: Array<String>){
   //calling the function.
   println("16 digit Random String: ${randomID()}");
}

Output

Following is the output −

16 digit Random String: XRKTgbJNzfDKzp0F
kotlin_arrays.htm
Advertisements