如何在 Kotlin 中简化它

安卓开发

Kotlin 中是否有更短的方法来编写以下代码:

private fun getMonth(monthText: String): Int {
    var x = arrayOf("january", "february", "jumper").indexOf(monthText)

    if (x >= 0)
        return x

    x = arrayOf("Januari", "Februari", "Maret").indexOf(monthText)

    if (x >= 0)
        return x

    throw Exception("Not found")

}

我必须对多种语言重复数组搜索,并希望避免重复重复的代码。注意:返回值必须指明月份。

弗兰克·弗格

出于性能原因,您应该比搜索更好地散列

private val monthByName = mapOf(
    "january" to 0,
    "february" to 1,
    "jumper" to 2,
    "Januari" to 0,
    "Februari" to 1,
    "Maret" to 2
)

private fun getMonth(monthText: String) = monthByName[monthText] ?: throw NoSuchElementException(monthText)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章