Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kotlin Get random string from array

Tags:

random

kotlin

New to kotlin and quite a few questions and answers, mostly in Java. After following the documentation and verifying against numerous SO questions/answers Android Studio is complaining about the following in a function. The function is

fun getRandomQuote() {
    val randomValue = Random.nextInt(quotes.size)
    //return quotes[randomValue]
    return quotes.get(randomValue)
}

quotes is an arrayOf(strings)

val quotes = arrayOf("Alert today – Alive tomorrow.",...)

It says for

quotes.get(randomValue)

That it should be a Unit but found String. randomValue should be an integer as defined by the docs using nextInt unless I misinterpreted the docs. I don't see the issue. I'm just trying to randomly return a string from the array. I thought maybe another false positive from studio so I cleaned the project but it stops here on building. Anyone see what it is I'm doing wrong.

like image 208
Micah Montoya Avatar asked Feb 16 '26 15:02

Micah Montoya


1 Answers

As the other answers said, your function is missing return type, so by default it's Unit. Specifying the return type as String fixes the error.

I'd like to propose another more succinct way to choose a random element from an array using the default random number generator: just use the random extension function available on collections and arrays.

    val colors = arrayOf("red", "blue", "yellow")
    val randomColor = colors.random()
like image 95
Ilya Avatar answered Feb 20 '26 01:02

Ilya