This article explores different ways to generate random numbers between the specified range in Kotlin.

1. Using random() function

A simple approach to retrieve an arbitrary element from the specified range is to use the random() function.

Download Code

Output (will vary):

7
5
9
8
8

 
You can call it without arguments or with a Random object as a randomness source.

Download Code

Output (will vary):

7
7
9
5
6

2. Using Random class

Kotlin offers the Random class in the kotlin.random package, which can generate random numbers. You can use its nextInt() function to get a pseudorandom integer value between 0 (inclusive) and the specified value (exclusive).

Following is a simple example demonstrating usage of this function, which generates a pseudorandom number between start and end:

Download Code

Output (will vary):

9
6
5
9
5

 
This works as nextInt(end - start + 1) will generate a random number between 0 and (end - start) and adding start to it will give a random number between start and end.

 
The nextInt() function is overloaded to generate an integer random value uniformly distributed between the specified range.

Download Code

Output (will vary):

8
5
6
8
6

3. Using Math.random() function

Another plausible way is to use the Math.random() function that returns a pseudorandom double value within the range [0.0, 1.0).

Download Code

Output (will vary):

7
7
8
8
5

 
It works as Math.random() generates a random double in range of [0.0, 1.0). When multiplied by ((end - start) + 1), the lower limit remains 0, but the upper limit becomes (end - start, end - start + 1). On casting to an Int and adding start, the range becomes [start, end].

4. Using SecureRandom class

To get a cryptographically strong random number generator, consider using the SecureRandom class from the java.security package. Here’s a working example:

Download Code

Output (will vary):

7
9
5
9
7

5. Using ThreadLocalRandom class

The recommended approach is to use the ThreadLocalRandom class to get better performance in multithreaded environments.

Download Code

Output (will vary):

6
7
9
6
6

6. Using shuffled() function

Finally, you can shuffle elements in the specified range and return the first or the last element after shuffling, which would be your random element.

Download Code

Output (will vary):

8
9
5
9
8

That’s all about generating random numbers between specified ranges in Kotlin.