Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the parameter in data class be var in Kotlin?

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
)
like image 658
HelloCW Avatar asked Apr 06 '18 08:04

HelloCW


People also ask

Can data class have var?

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.

How do you pass parameters in Kotlin?

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.

Can data class inherit Kotlin?

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.

What is the difference between data class and class in Kotlin?

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.


1 Answers

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

like image 69
Rohit5k2 Avatar answered Nov 07 '22 18:11

Rohit5k2