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
)
To ensure consistency and meaningful behavior of the generated code, data classes have to fulfill the following requirements: The primary constructor needs to have at least one parameter. All primary constructor parameters need to be marked as val or var . Data classes cannot be abstract, open, sealed, or inner.
In Kotlin, You can pass a variable number of arguments to a function by declaring the function with a vararg parameter. a vararg parameter of type T is internally represented as an array of type T ( Array<T> ) inside the function body.
There is no way to generate the correct value-based equals() without violating the Liskov Principle. That's why Kotlin doesn't allow inheritance for Data classes.
A data class is a class that only contains state and does not perform any operation. The advantage of using data classes instead of regular classes is that Kotlin gives us an immense amount of self-generated code.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With