Copilot: Kotlin create a function to generate a random number between 1 and 6
Video: Copilot: Kotlin create a function to generate a random number between 1 and 6 by Taught by Celeste AI - AI Coding Coach
Watch full page →Copilot: Kotlin create a function to generate a random number between 1 and 6
Generating random numbers in Kotlin is straightforward using the standard library. This example demonstrates how to create a simple function that returns a random integer between 1 and 6, simulating a dice roll.
Code
import kotlin.random.Random
// Function to generate a random number between 1 and 6
fun rollDice(): Int {
// Random.nextInt(from, until) generates a number from 'from' (inclusive) to 'until' (exclusive)
return Random.nextInt(1, 7) // 7 is exclusive, so result is between 1 and 6
}
fun main() {
val result = rollDice()
println("You rolled a $result")
}
Key Points
- Kotlin's Random.nextInt(from, until) generates random integers in a specified range, with 'until' being exclusive.
- To include 6 in the range, specify 7 as the exclusive upper bound.
- Wrapping the random logic in a function makes it reusable and clear.
- Importing kotlin.random.Random is necessary to access the random number generator.