Based on Paul Hicks answer, I wanted to use a custom string as input. In my case, uppercase and lowercase alphanumeric characters. Random().ints(...) also did not work for me, since using it required API level 24 on Android.
Here's how I do it with the Kotlin Random abstract class:
import kotlin.random.Random object IdHelper { private val ALPHA_NUMERIC = ('0'..'9') + ('A'..'Z') + ('a'..'z') private const val LENGTH = 20 fun generateId(): String { return List(LENGTH) { Random.nextInt(0, ALPHA_NUMERIC.size) } .map { ALPHA_NUMERIC[it] } .joinToString(separator = "") } }
The process and how it works is similar to many other answers already posted here:
- Create a list of
LENGTH length numbers that correspond to the source string index values, which in this case is ALPHA_NUMERIC - Match these numbers with the original string, converting each numerical index into a character value.
- Convert the resulting list of characters to a string by concatenating them with an empty string as a delimiter character.
- Return the resulting string.
Easy to use, just call it as a static function: IdHelper.generateId()
source share