This article explores different ways to randomly select an item from a List in Kotlin.

1. Using random() function

Since Kotlin 1.3, you can use the random() function to return a random element from a list. A typical invocation for this method would look like below. Note that it throws NoSuchElementException if the list is empty.

Download Code

2. Using Random.nextInt() function

Before Kotlin 1.3, you can generate a random index and use that index to get the random value. This can be achieved using the Random.nextInt() function, which returns a random value uniformly distributed between 0 (inclusive) and the specified bound (exclusive).

Download Code

3. Using shuffled() function

Another solution is to randomize the list using the shuffled() function, and return the value present at the first or the last index. This would translate to a simple code below:

Download Code

That’s all about randomly selecting an item from a List in Kotlin.