pilgr / Paper

Paper is a fast NoSQL-like storage for Java/Kotlin objects on Android with automatic schema migration support.
Apache License 2.0
2.35k stars 234 forks source link

Respect kotlin non-null types when structure changes #155

Closed melbaldove closed 4 years ago

melbaldove commented 5 years ago

Hello,

Please respect kotlin non-null fields when structure changes. Setting null to non-null Kotlin fields causes apps that rely on these fields to crash. We should instead set a non-null default value for these fields.

pilgr commented 5 years ago

Since on the JVM level there is no nullable or non-nullable types it's quite hard to add such feature out of the box. But I found a workaround which actually works:

data class Foo(var name: String)

val result = Paper.book().read<Foo>("key")
@Suppress("SENSELESS_COMPARISON")
if (result.name == null) result.name = "default"
assertThat(result).isEqualTo(Foo("default"))

So just check the changed type on read and set default value when it's null. Yeah, it's far from elegant solution but I can't find better one so far.

melbaldove commented 5 years ago

@pilgr Thanks. That is what I am doing so far.