Line At A Time
Lesson 23: Random Number Function
Random Number Function Write your own function and call it.
1import kotlin.random.Random
2
3fun main() {
4 randomNumber()
5}
6
7private fun randomNumber() {
8 val randomValue = Random.nextInt(10)
9 println(randomValue)
10}
Terminal
$ kotlinc Main.kt -include-runtime -d Main.jar
$ java -jar Main.jar
(prints a random number, different every run)
Every line, explained
import kotlin.random.Random
import lines go at the very top of a Kotlin file and bring in extra tools. kotlin.random.Random is Kotlin's random-number helper; we need it for Random.nextInt below.
fun main() {
Every Kotlin program starts at the main function. When you run the program, Kotlin looks for fun main() and runs everything between its { and } from top to bottom.
randomNumber()
This line calls (runs) the randomNumber function we define below. When Kotlin reaches this line it jumps into randomNumber, runs its code, then comes back here. Remember: the program still starts at main; defining a function does nothing until somebody calls it.
}
This closing curly brace } ends the main function. In Kotlin every opening brace { must have a matching closing brace }.
private fun randomNumber() {
fun defines a function: a named block of code you can run whenever you want by calling its name. private just means only this file can use it. Kotlin does not mind that this function is written below the line in main that calls it.
val randomValue = Random.nextInt(10)
Random.nextInt(10) hands back a random whole number from 0 up to (but not including) 10, so 0 to 9, different every time you run the program!
println(randomValue)
println(...) prints whatever is inside the round brackets to the terminal, then moves to a new line. All lowercase, and no semicolon at the end; Kotlin does not need them. Prints whichever number came up this time.
}
This } closes the function.