I'm trying to simplify Parcelable code in Kotlin:
public class C() : Parcelable {
var b1: Boolean = false
var b2: Boolean = false
var b3: Boolean = false
var i1: Int = 0
var i2: Int = 0
val parcelBooleans = listOf(b1, b2, b3)
val parcelInts = listOf(i1, i2)
override fun writeToParcel(p: Parcel, flags: Int) {
parcelBooleans.forEach { p.writeBoolean(it) }
parcelInts.forEach { p.writeInt(it) }
}
private fun readFromParcel(p: Parcel) {
parcelBooleans.forEach{ it = p.readBoolean() } // does not compile as "it" is a "val"
}
// ... parcel creator bla bla
}
writeBoolean() and readBoolean() are extension functions.
Is there a way to have a forEach on list with an assignable "it"?
Update: in a comment to one of the answers the author clarifies this question as:
My point is that my list is not mutable, the elements inside are. Elements are my properties. But I'm realizing that maybe, listOf is making a value copy of my properties… so either I must rely on reflection, or wrapping basic type into an class to allow change to their value.
The intent is via the readonly list parcelBooleans which holds references to b1, b2, and b3 modify the values of b1, b2, and b3; but not mutating the list itself.