
- Kotlin - Home
- Kotlin - Overview
- Kotlin - Environment Setup
- Kotlin - Architecture
- Kotlin - Basic Syntax
- Kotlin - Comments
- Kotlin - Keywords
- Kotlin - Variables
- Kotlin - Data Types
- Kotlin - Operators
- Kotlin - Booleans
- Kotlin - Strings
- Kotlin - Arrays
- Kotlin - Ranges
- Kotlin - Functions
- Kotlin Control Flow
- Kotlin - Control Flow
- Kotlin - if...Else Expression
- Kotlin - When Expression
- Kotlin - For Loop
- Kotlin - While Loop
- Kotlin - Break and Continue
- Kotlin Collections
- Kotlin - Collections
- Kotlin - Lists
- Kotlin - Sets
- Kotlin - Maps
- Kotlin Objects and Classes
- Kotlin - Class and Objects
- Kotlin - Constructors
- Kotlin - Inheritance
- Kotlin - Abstract Classes
- Kotlin - Interface
- Kotlin - Visibility Control
- Kotlin - Extension
- Kotlin - Data Classes
- Kotlin - Sealed Class
- Kotlin - Generics
- Kotlin - Delegation
- Kotlin - Destructuring Declarations
- Kotlin - Exception Handling
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