Reputation: 131
I'm a beginner in Kotlin! Can we explain the difference between these classes in Kotlin
class Person(val name: String, val age: Int)
class Person(name: String, age: Int)
class Person(var name: String,var age: Int)
And how I add getter and setter for data class in Kotlin?
Upvotes: 2
Views: 74
Reputation: 20102
First you should try to read the difference in the manual:
https://kotlinlang.org/docs/reference/data-classes.html
https://kotlinlang.org/docs/reference/classes.html
But lets try to explain this:
class Person(val name: String, val age: Int)
The Kotlin compiler will generate for both constructor arguments corresponding fields storing the values and will generate respecting getters. The values are immutable because of the keyword val
so there will not be any setters.
class Person(name: String, age: Int)
The arguments are only passed to the constructor but not stored as fields. So there will also be no getters and setters.
class Person(var name: String, var age: Int)
Like in the first example the values are stored in generated fields. But the values are mutable because of the keyword var
so the compiler will generate getters and setters.
data
is an additional (optional) keyword to put in front of the class
declaration. This will in addition to the getters and setters generate a toString
method printing the values of all attributes with their names and a hashCode
method taking every value into account. As getters and setters are generated for data
classes you don't need to add them manually.
Kotlin is a lot about reducing the manual work required to do by the developer in Java to be done by the compiler of Kotlin.
Upvotes: 6