Bo Z
Bo Z

Reputation: 2607

Is there an easy to get random number from the range in kotlin?

I have checked THIS example but my studio do not see this function and not import is. Is there a similar way ?

This one not import val randomNumber = (100..200).random()

Upvotes: 0

Views: 165

Answers (2)

Yunfei Chen
Yunfei Chen

Reputation: 626

If you really need to avoid that library here is a roundabout way of doing it:

val random = Random
val myInt = 100 + random.nextInt(100)
println(myInt)

Note that myInt will be between 100 and 200.

Upvotes: 0

Abhinav Chauhan
Abhinav Chauhan

Reputation: 1384

@SinceKotlin("1.3")
@kotlin.internal.InlineOnly
public inline fun IntRange.random(): Int {
return random(Random)
}

random() is extension function on IntRange in the ktx library introduced in kotlin 1.3 make sure you're using kotlin 1.3 or above and using core ktx implementation 'androidx.core:core-ktx:1.7.0' not implementation 'androidx.core:core:1.7.0'

you can also achieve same thing using Random.nextInt(100,200)

Upvotes: 1

Related Questions