kotlin Get random string from array

断了今生、忘了曾经 提交于 2021-01-29 06:00:23

问题


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.


回答1:


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.




回答2:


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



回答3:


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
}


来源:https://stackoverflow.com/questions/59183635/kotlin-get-random-string-from-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!