Home > Software engineering >  Is there an easy to get random number from the range in kotlin?
Is there an easy to get random number from the range in kotlin?

Time:06-23

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()

CodePudding user response:

@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)

CodePudding user response:

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.

  • Related