I'm a beginner of Kotlin, I have read some sample code about data class, it seems that the parameter are all val type just like Code A
I need to change some values of data class MSetting, so I design the Code B, could you tell me whether the Code B is good way?
Code A
data class MSetting (
val _id: Long,
val name: String,
val createdDate: Long,
val description: String
)
Code B
data class MSetting (
var _id: Long,
var name: String,
var createdDate: Long,
var description: String
)
it seems that the parameter are all
val
type...
NO
could you tell me whether the Code B is good way?
The difference between val
and var
: Properties declared with val
can't be updated over time; its just like constants in java. Properties declared with var
can be changed overtime.
It totally depends on your requirement. If you need to change properties over time then go for var
; val
otherwise. You can mix both in a object without any issue.
Read more about properties in Kotlin documentation here https://kotlinlang.org/docs/reference/properties.html