Are i understand something wrong or it's kotlin bu...
# android
j
Are i understand something wrong or it's kotlin bug? I have : data class Foo ( val initializationType: InitializationType) { val isInitDefault = initializationType == InitializationType.Default } and when i call this val it's working incorrect, but when i transform it to fun or just add custom get() = initializationType == InitializationType.Default it start working like it should what the problem? P.S. InitializationType it's enum
g
what exactly “working incorrect”? Maybe your initializationType is mutable in your code. Don’t forget that isInitDefault caches result and do not update value on initializationType change) Just show some example, you can try to reproduce it on try.kotlinlang.org and share your code
j
it's val
g
So, maybe you could share some self-contained example
j
group.fields.any { it.fieldType.initializationType == InitializationType.Optional } // true group.fields.any { it.fieldType.isInitOptional() } // false
g
what is group and fields? Is that reflections API?
j
no, it's data classes
it came from back
g
Oh, so you use something like Gson to map backend response to data class?
j
yes
g
This is because of way how Gson works. If your class do not have default constructor Gson uses sun.misc.Unsafe to create instance and set fields without calling constructor, so your field not initialised
it’s known problem of some Java-only json mappers: Use default constructor (just add default values to all the properties or use default constructor compiler plugin) Use some another solution for mapping json to classes that respects nullability and probably support Kotlin data classes (moshi-kotlin, kotshi, #klaxon, kotlinx.serialization #serialization or something else, don’t know such libraries for Gson tho, only Gson + AutoValue)
Or use method/getter/extension function of course, that doesn’t have such problem
j
ohh thank you very much!!!
g
Also because of this default properties values don’t work if you don’t have default constructor, be careful with this
and also Gson can write null to non-null field because doesn’t respect nullability