https://kotlinlang.org logo
#android
Title
# android
j

Jacks0n23

04/09/2018, 2:09 PM
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

gildor

04/09/2018, 2:41 PM
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

Jacks0n23

04/09/2018, 2:46 PM
it's val
g

gildor

04/09/2018, 2:48 PM
So, maybe you could share some self-contained example
j

Jacks0n23

04/09/2018, 2:58 PM
group.fields.any { it.fieldType.initializationType == InitializationType.Optional } // true group.fields.any { it.fieldType.isInitOptional() } // false
g

gildor

04/09/2018, 3:01 PM
what is group and fields? Is that reflections API?
j

Jacks0n23

04/09/2018, 3:01 PM
no, it's data classes
it came from back
g

gildor

04/09/2018, 3:02 PM
Oh, so you use something like Gson to map backend response to data class?
j

Jacks0n23

04/09/2018, 3:03 PM
yes
g

gildor

04/09/2018, 3:04 PM
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

Jacks0n23

04/09/2018, 3:08 PM
ohh thank you very much!!!
g

gildor

04/09/2018, 3:10 PM
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