kotlin从数组中获取随机字符串 [英] kotlin Get random string from array
问题描述
kotlin的新知识和很多问题和答案,大部分是Java语言.在遵循文档并针对众多SO进行验证后,问题/答案 Android Studio抱怨关于以下功能.功能是
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)
}
引号是arrayOf(strings)
quotes is an arrayOf(strings)
val quotes = arrayOf("Alert today – Alive tomorrow.",...)
说
quotes.get(randomValue)
应该是一个 Unit ,但是找到了 String .randomValue应该是文档使用nextInt,除非我误解了文档.我没有看到这个问题.我只是想从数组中随机返回一个字符串.我以为可能是工作室的另一个误报,所以我清理了项目,但在此停止建设.有人看到我在做什么错了.
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.
推荐答案
您的函数未指定返回类型,这就是为什么编译器期望'Unit'与Java中的void相同的原因.
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]
}
请参阅文档以获取 Kotlin函数作为参考.
See the docs for Kotlin functions as a reference.
将索引用于带方括号的数组而不是get()函数也更容易.
It is also more kotliny to use indexing for arrays with square brackets instead of get() function.
这篇关于kotlin从数组中获取随机字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!