Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Kotlin中以优雅的方式返回结果?_Kotlin - Fatal编程技术网

如何在Kotlin中以优雅的方式返回结果?

如何在Kotlin中以优雅的方式返回结果?,kotlin,Kotlin,代码A和代码B可以很好地工作,但我认为在Kotlin中这不是一个好方法,有没有一种优雅的方法可以做到这一点?谢谢 代码A private fun getIndexByIntent(data: Intent): Int{ var index=-1 var id=getIDByIntent(data) for (aIndex in mListBackupItem.indices){ if (mListBackupItem[

代码A和代码B可以很好地工作,但我认为在Kotlin中这不是一个好方法,有没有一种优雅的方法可以做到这一点?谢谢

代码A

  private fun getIndexByIntent(data: Intent): Int{
        var index=-1
        var id=getIDByIntent(data)

        for (aIndex in mListBackupItem.indices){
            if (mListBackupItem[aIndex]._id==id){
                index=aIndex
            }
        }    
        return index
    }
代码B

private fun getIndexByIntent(data: Intent): Int{
        var index=-1
        var id=getIDByIntent(data)

        for (aIndex in mListBackupItem.indices){
            if (mListBackupItem[aIndex]._id==id){
                return aIndex
            }
        }
        return index
    }

这个精确的逻辑已经以函数的形式在标准库中实现,请使用:

fun getIndexByIntent(data: Intent) : Int {
    val id = getIDByIntent(data)
    return mListBackupItem.indexOfFirst { it._id == id }
}

代码B:返回aIndex in for loopCode B有两个返回,代码A只有一个返回