Why can't I initialize a "@Transient" property in init block?
Copy code
Serializable
data class Item(
val count: Int,
val price: Int
) {
@Transient
val totalPrice = count*price //this works
@Transient
val totalPrice2 //This property is marked as @Transient and therefore must have an initializing expression
init {
totalPrice2 = count*price //this does not
}
}
a
Alex Prince
08/20/2024, 2:39 PM
because it's a Val. Vals are immutable and have to be set where they're declared.
If you want to do it in the init block, you could make it a var (though then you lose the immutablility, which, to me anyway, is less than ideal)
v
Vladimir Vainer
08/20/2024, 2:40 PM
If the property is not marked as @Transient
I can init val inside init block
a
Alex Prince
08/20/2024, 2:40 PM
corrected my msg but lateinit would also require the var I think, need more coffee
c
Chris B
08/20/2024, 2:41 PM
It does.
v
Vladimir Vainer
08/20/2024, 2:43 PM
There is inconsistency.
If i have a val property that is not transient, but initialize it with default value,
It behaves like transient anyway.
But if i move the initialization to the init block, then it's no longer transient.
The question is what the difference?
If i initialize someting in the init block, it's the same as default value, it's still a val.
So why it doesn't work
m
Michael Krussel
08/20/2024, 2:47 PM
I do wonder if this is something special due to data class or Serializable class or both.
I know in general (on JVM) if you initialize in the constructor things have the default value in the parent class init block.