https://kotlinlang.org logo
#getting-started
Title
# getting-started
y

y

02/29/2024, 10:09 AM
my class has a
val expensiveProperty: Foo? by lazy { ... }
. I'd like to have it skipped by
kotlinx
serialization and deserialization. is this possible?
y

y

02/29/2024, 10:26 AM
this gives me
Property does not have backing field which makes it non-serializable and therefore @Transient is redundant
but (and I could be wrong here!) I do observe this new lazy initializer getting called by serialization
on second glance, might be our own code interacting with this.
j

Johan

02/29/2024, 10:32 AM
I think this should work
Copy code
@Serializable
class Bar {
    @delegate:Transient
    val expensiveProperty: Foo by lazy { Foo() }
}

data class Foo(val value : String = "")
fun main() {
    val bar = Json.decodeFromString<Bar>("""{}""")
    val barJson = Json.encodeToString(bar)
    println(barJson)
    println(bar.expensiveProperty.value)
}
a

asdf asdf

02/29/2024, 3:11 PM
If you have a delegated field / field with a getter, it is already skipped by kotlinx serialization, so @Transient isn’t needed. You can just keep the code as it is and the property won’t be serialized
👍 1
y

y

02/29/2024, 3:12 PM
yeah, that's what I gathered. so it must be our custom deserialization shenanigans
2 Views