android - Kotlin: assignable "it"? -
i'm trying 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{ = p.readboolean() } // not compile "it" "val" } // ... parcel creator bla bla }
writeboolean() , readboolean() extension functions.
is there way have foreach on list assignable "it"?
update: in comment 1 of answers author clarifies question as:
my point list not mutable, elements inside are. elements properties. i'm realizing maybe, listof making value copy of properties… either must rely on reflection, or wrapping basic type class allow change value.
the intent via readonly list parcelbooleans
holds references b1
, b2
, , b3
modify values of b1
, b2
, , b3
; not mutating list itself.
update: kt-7033 has been fixed, answer works without requiring kotlin-reflect.jar
i think simple way achieve wants using property references, note should provide kotlin-reflect.jar in classpath (until kt-7033 not fixed). additionally may simplified after kt-6947 fixed.
public class c_by_reflection() : 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.get(this)) } parcelints.foreach { p.writeint(it.get(this)) } } private fun readfromparcel(p: parcel) { parcelbooleans.foreach{ it.set(this, p.readboolean()) } } // ... parcel creator bla bla }
another simple solution using delegated properties:
public class c_by_delgates() : parcelable { val mapbooleans = hashmapof<string, any?>() var b1: boolean mapbooleans var b2: boolean mapbooleans var b3: boolean mapbooleans val mapints = hashmapof<string, boolean>() var i1: int mapints var i2: int mapints override fun writetoparcel(p: parcel, flags: int) { mapbooleans.foreach { p.writeboolean(it.value boolean) } mapints.foreach { p.writeint(it.value int) } } private fun readfromparcel(p: parcel) { mapbooleans.foreach { mapbooleans[it.key] = p.readboolean() } } // ... parcel creator bla bla }
Comments
Post a Comment