random number in Kotlin

How to Generate Random Number in Kotlin

In this article we will show you how to generate a random number in Kotlin. This is quite useful for testing purposes specially, although there are also some other applications where we will need to use random numbers.

Let’s start and see how can we achieve this in Kotlin!

Kotlin Random class

Kotlin provides a class called Random, which provides a Default companion object that can be used to generate a variety of random values for certain types.

We will start by generating a single random number, let’s see how!

Single Values

If we need to generate a single random Int, this is as simple as doing this:

    @Test
    fun `should generate a random int`() {

        val number = Random.nextInt()

        assertThat(number)
            .isGreaterThanOrEqualTo(Int.MIN_VALUE)
            .isLessThanOrEqualTo(Int.MAX_VALUE)
    }

Using nextInt will generate any value of Int within Int.MIN_VALUE and Int.MAX_VALUE, as you can see in our assertion in the test. What if we want to generate a number within a given range? This is quite easy too!

The method nextInt accepts the limits we’d like our number to be generated within. For instance, we could do the following:

    @Test
    fun `should generate a random int within limits`() {

        val number = Random.nextInt(0, 10)

        assertThat(number)
            .isGreaterThanOrEqualTo(0)
            .isLessThanOrEqualTo(10)
    }

It’s quite simple, isn’t it? There’s one more option that could be used in this method, we can also specify an upper limit only. For example, something like this:

    @Test
    fun `should generate a random int with upper limit`() {

        val number = Random.nextInt(10)

        assertThat(number)
            .isGreaterThanOrEqualTo(0)
            .isLessThanOrEqualTo(10)
    }

You will notice that the lower limit is still zero. This is because this method generate non-negative numbers with an upper limit specified as argument.

Now that you’ve seen the different options for nextInt method, you can also generate any of the other number types in Kotlin in exactly the same way. You can also use:

And also some of their “unsigned” equivalents:

An example using unsigned integers would be:

    @Test
    fun `should generate a random unsigned int with upper limit`() {

        val number = Random.nextUInt(10u)

        assertThat(number)
            .isLessThanOrEqualTo(10u)
    }

You can see how in Kotlin, unsigned types have to be suffixed with “u” character. You can read more about unsigned integers here.

All of them work in exactly the same way. As always, Kotlin is quite intuitive to use by developers.

What if we next to generate multiple random values?

Kotlin Random Number - Multiple Values
Photo by James Orr on Unsplash

Multiple Values

In Kotlin, it’s very easy to generate a list of random numbers. You can do something as the following for example:

    @Test
    fun `should generate a list of random numbers`() {

        val numbers = List(10) {
            Random.nextInt(0, 10)
        }

        assertThat(numbers).allMatch {  number -> number in 0..10 }
    }

This will generate a list of ten random Int elements. As you can see, we can do this in a very simple and concise way!

Now that we’ve seen how to generate single and multiple values, let’s find out what other ways could we use to generate random numbers.

Random method

Another way to generate random numbers easily in Kotlin is by using a very useful method provided in the Collection interface or in any of the range objects, this is random() method. Its use is very simple, let’s see how it’d look like with a unit test:

    @Test
    fun `should pick a random number from a range`() {

        val number = (0..100).random()

        assertThat(number)
            .isGreaterThanOrEqualTo(0)
            .isLessThanOrEqualTo(100)
    }

You just have to define an IntRange and call random() method right after that.

Let’s now look at one last way to generate random numbers.

Shuffled method

One more way of generating a random number is by shuffling an Iterable of elements and picking the first or last element. For instance, we could write the following example:

    @Test
    fun `should pick a random number from a range using shuffled`() {

        val number = (0..100).shuffled().first()

        assertThat(number)
            .isGreaterThanOrEqualTo(0)
            .isLessThanOrEqualTo(100)
    }

As you can see, very straightforward again. What if instead of a range we want to use a collection? It’ll be very similar.

    @Test
    fun `should pick a random number from a list using shuffled`() {

        val number = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).shuffled().first()

        assertThat(number)
            .isGreaterThanOrEqualTo(0)
            .isLessThanOrEqualTo(10)
    }

That’s it! You can see how easy is to generate random numbers in Kotlin.

Conclusion

In this article we have learned how to generate single and multiple random values in Kotlin in a very simple manner. If we compare this to Java, again Kotlin can be considered more “developer-friendly” to achieve a task like this one.

This is all from us today! We are hoping you learned something new today and enjoyed your time with us.

If you are interested in more Kotlin articles, you can find more articles about Kotlin written by us here.

Looking forward to seeing you again! Please follow us for more interesting content!

Thanks for reading us!