Kotlin how to return a SINGLE object from a list that contains a specific id?

后端 未结 4 1260
迷失自我
迷失自我 2020-12-31 01:58

Good day, i\'m stuck figuring out how to get a single object from a list, i did google but all the topics show how to return a List with sorted objects or somet

4条回答
  •  别那么骄傲
    2020-12-31 02:43

    You can use this extension function also which return pair Pair(Boolean,T)

    e.g

    val id=2
    val item= myList.customContains{it-> it.userId ==id}
    
    if(item.first){
    item.second  //your object
    //    your code here
    }else{
    // if item no present
    }
    
    
    
    
    fun  List.customContains(function: (currentItem: E) -> Boolean): Pair {
            for (current in 0 until this.size) {
                if (function(this[current])) {
                    return Pair(true, this[current])
                }
            }
            return Pair(false, null)
        }
    

提交回复
热议问题