Skip to content
DeveloperMemos

Getting a Random Boolean in Kotlin

Kotlin, Boolean, Random1 min read

In Kotlin, a boolean is a data type that can hold either the value true or false. There are various ways to generate a random boolean in Kotlin, and in this article, we will explore some of the most commonly used methods.

Method 1: Using the Random class

One way to generate a random boolean in Kotlin is by using the Random class from the java.util package. This class provides several methods for generating random values, including nextBoolean(), which returns a random boolean value.

Here is an example of how to use the Random class to generate a random boolean:

1import java.util.Random
2
3fun main() {
4 val random = Random()
5 val randomBoolean = random.nextBoolean()
6 println(randomBoolean)
7}

The nextBoolean() method returns a random boolean value with an equal probability of returning true or false.

Method 2: Using the kotlin.random package

Another way to generate a random boolean in Kotlin is by using the kotlin.random package, which provides several functions for generating random values. One of these functions is Random.nextBoolean(), which returns a random boolean value.

Here is an example of how to use the kotlin.random package to generate a random boolean:

1import kotlin.random.Random
2
3fun main() {
4 val randomBoolean = Random.nextBoolean()
5 println(randomBoolean)
6}

Like the Random class from the java.util package, the Random.nextBoolean() function returns a random boolean value with an equal probability of returning true or false.

Method 3: Using the Random.nextInt() function

Another way to generate a random boolean in Kotlin is by using the Random.nextInt() function from the kotlin.random package. This function returns a random integer value within a specified range.

To use this function to generate a random boolean, we can specify a range of 0 to 1 and then check if the resulting integer is 0 or 1. If the integer is 0, we can return false, and if it is 1, we can return true.

Here is an example of how to use the Random.nextInt() function to generate a random boolean:

1import kotlin.random.Random
2
3fun main() {
4 val randomBoolean = if (Random.nextInt(0, 2) == 0) false else true
5 println(randomBoolean)
6}

This method allows us to generate a random boolean value with an equal probability of returning true or false.

Conclusion

In this article, we have explored three different methods for generating a random boolean in Kotlin. We saw how to use the Random class from the java.util package, the kotlin.random package, and the Random.nextInt() function to generate a random boolean value.

No matter which method you choose, you can use these techniques to add an element of randomness to your Kotlin code.