HelloCW
HelloCW

Reputation: 2325

Is there a simple way to get a object by _id in Kotlin?

I'm a beginner of Kotlin, I hope to get a object by _id in the following data structure, so I write the fun getMDetailByID(aMDetailsList:MDetailsList, _id:Long)... which is a traditional method.

But I think the fun is too complex, is there a simple way do that? such as use Lambda expression.

class UIMain : AppCompatActivity() {

    data class BluetoothDef(val Status:Boolean=false)
    data class WiFiDef(val Name:String, val Status:Boolean=false)

    data class MDetail (
            val _id: Long,
            val bluetooth: BluetoothDef,
            val wiFi:WiFiDef
    )

    data class MDetailsList(val mListMetail: MutableList<MDetail>)


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.layout_main)

        var mBluetoothDef1=BluetoothDef()
        var mWiFiDef1=WiFiDef("MyConnect 1",true)
        var aMDetail1= MDetail(5L,mBluetoothDef1,mWiFiDef1)

        var mBluetoothDef2=BluetoothDef(true)
        var mWiFiDef2=WiFiDef("MyConnect 2")
        var aMDetail2= MDetail(6L,mBluetoothDef2,mWiFiDef2)

        val mListMetail:MutableList<MDetail> = mutableListOf(aMDetail1,aMDetail2)

        var aMDetailsList=MDetailsList(mListMetail)

        var c=getMDetailByID(aMDetailsList,5L)

    }

    fun getMDetailByID(aMDetailsList:MDetailsList, _id:Long):MDetail?{
        var aMDetail: MDetail?=null

        var a=aMDetailsList.mListMetail

        for (b in a){
            if (b._id==_id){
                aMDetail=b
            }
        }

        return aMDetail

    }

}

Upvotes: 0

Views: 391

Answers (3)

Alexey Romanov
Alexey Romanov

Reputation: 170835

A faster and simpler alternative to current answers (it's also better than your original code, since it doesn't always need to traverse the entire list):

fun getMDetailByID(aMDetailsList: MDetailsList, _id: Long) = 
    aMDetailsList.mListMetail.findLast { it._id == _id }

Also, consider whether you actually benefit from defining MDetailsList as a class instead of directly using (Mutable)List<MDetail> or making it a typealias. There are cases in which you do need such a type, but they aren't that common.

Upvotes: 2

Ngima Sherpa
Ngima Sherpa

Reputation: 1555

Simpler code can be like:

fun getMDetailByID(aMDetailsList: MDetailsList, _id: Long) = aMDetailsList.mListMetail.filter { it._id == _id }.lastOrNull()

Upvotes: 1

Ekeko
Ekeko

Reputation: 1979

There is a simpler way using lambdas, indeed. You could replace your function code by:

fun getMDetailByID(aMDetailsList: MDetailsList, _id: Long): MDetail? {
    return aMDetailsList.mListMetail.filter { it._id == _id }.lastOrNull()
}

It will, like your implementation did, return the last matching element or null if there is none.

Upvotes: 1

Related Questions