
- 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 - 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