Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Multiple Layer it Reference

How do you reference the second layer "it" from the third layer without creating a new val/var? I know you can do val mydata = it and then do mydata.id.toString() I was just wondering is there something in Kotlin that can let me reference an it from a higher level?

data.arrayresults.forEach {
    val result = it

    result.myData.let {
        val itemView - inflater.inflate(R.layout.somelayout)

        itemView.setOnClickListener(View.OnClickListener {

            // the it references the view but I want it to reference the result.myData
            SomeActivity.startActivity(context, it.id.toString())
        })
    }
}
like image 465
JPM Avatar asked Jun 22 '26 04:06

JPM


1 Answers

No, the it symbol always references the innermost implicit single lambda parameter.

To resolve this, and also to improve the code readability, use named lambda parameters every time when you have nested lambdas with parameters, as suggested in the Coding conventions:

data.arrayresults.forEach { result ->    
    result.myData.let { myData ->
        val itemView - inflater.inflate(R.layout.somelayout)

        itemView.setOnClickListener(View.OnClickListener { view ->

            // the it references the view but I want it to reference the result.myData
            SomeActivity.startActivity(context, myData.id.toString())
        })
    }
}
like image 159
hotkey Avatar answered Jun 23 '26 17:06

hotkey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!