https://kotlinlang.org logo
#announcements
Title
# announcements
l

LastExceed

09/01/2019, 7:38 AM
Copy code
class Human(val name: String, age: Int) {
    var age = age
        private set
    
    fun birthday() {
        //party hard
        age++
    }
}
can this be simplified somehow or is it good as is?
p

Pavlo Liapota

09/01/2019, 7:47 AM
If immutable class will work in your case, then you can write:
Copy code
data class Human(
    val name: String,
    val age: Int
)

fun Human.birthday() = copy(age = age + 1)
In this case
birthday
returns new instance instead of modifying existing one.
l

LastExceed

09/01/2019, 7:50 AM
nah it needs to be mutable, i was wondering if its possible to set getters and setters for variables declared in the primary constructor (like
name
in my example)
d

dawidhyzy

09/01/2019, 8:17 AM
Copy code
data class Human(
    val name: String,
    private var age: Int
) {
    fun birthday() {
        //party hard
        age++
    }
}
l

LastExceed

09/01/2019, 8:18 AM
@dawidhyzy in your example the setter of
age
isn't private, is it?
d

dawidhyzy

09/01/2019, 8:18 AM
next time post this type of question in #getting-started
now it is
l

LastExceed

09/01/2019, 8:18 AM
but now the getter is private too
d

dawidhyzy

09/01/2019, 10:15 AM
then I think this is the best you can get:
Copy code
class Human(val name: String, age: Int) {
    var age = age
        private set
    
    fun birthday() {
        //party hard
        age++
    }
}