This article explores different ways to generate a random character in Kotlin.

1. Using CharRange.random() function

To generate a random element between a specific range of characters, call the random() function on the Kotlin CharRange. For instance, the following code generates a random character in the range A-Z.

Download Code

 
Don’t call random() function on an empty range, otherwise IllegalArgumentException is thrown. We can easily extend the solution to generate a random character in the alphanumeric range. The alphanumeric range consists of digits, lowercase, and uppercase characters.

Download Code

2. Using Random.nextInt() function

Alternatively, use the nextInt() function from the kotlin.random.Random class to generate a random character between some specific character range, as shown below.

Download Code

 
To generate a random value from the lowercase and uppercase characters range, do like:

Download Code

 
Finally, to generate a random character using any custom character set, do as follows.

Download Code

That’s all about generating a random character in Kotlin.