Ad space (banner)
๐ŸŽฏKotlin Lessons
Lesson 53 / 68

Generating Random Numbers

In this lesson you will learn how to generate random numbers with the random extension function in Kotlin, so you can build things with an element of chance such as dice or rock-paper-scissors. This is for anyone searching for "Kotlin random number generation".

The .random() extension function on a range or a list gives you a random number, or a randomly chosen value from a list. Use it for dice rolls and raffles. The result changes every time you run it.

The sample code rolls a die from 1 to 6 with (1..6).random() and picks one of Rock, Scissors, and Paper with choices.random(). Notice the consistent design that lets the same .random() work on both a range and a list.

A common stumbling block for beginners is that calling .random() on an empty list throws. You have to be sure the list is not empty before using it.

In real-world development random values are essential wherever you want an unpredictable element, from shuffling in a game to sampling in a simulation.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Kotlin directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)