Micah Montoya
Micah Montoya

Reputation: 767

kotlin Get random string from array

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.

Upvotes: 3

Views: 8868

Answers (3)

Ilya
Ilya

Reputation: 23144

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

Upvotes: 9

nulldroid
nulldroid

Reputation: 1230

Your function doesn't specify a return type, that's why the compiler is expecting 'Unit' which would be the same as void in Java.

When you want to return a String, you need to specify it like so

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

See the docs for Kotlin functions as a reference.

It is also more kotliny to use indexing for arrays with square brackets instead of get() function.

Upvotes: 2

vikas kumar
vikas kumar

Reputation: 11018

You are just missing this

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

Since you are returning from the function which is a String. If we don't return anything, it means its Unit in Kotlin and we don't have to mention it and return it. Other than that we got to mention what we are returning by putting right to the colon. ex:

fun getRandomQuote(): String{
  //something goes here
}

Upvotes: 0

Related Questions