Reputation: 113
I'm following a course in kotlin and they speak about how to make a special setter but I don't know how to make it working here is my code :
class Course (val id:Int, title:String, var duree:Int, var state:Boolean){
var title:String = title
get(){return field}
set(value){field = "my awesome" + value}
}
fun main(args: Array<String>) {
var myCourse:Course = Course (0, "stuff", 50, true)
println(myCourse.title)
}
but it keep output 'stuff' instead of 'my awesome stuff'
Upvotes: 1
Views: 61
Reputation: 15183
var myCourse:Course = Course(0, "stuff", 50, true)
With the above line of code, the Course
object is initialized with the constructor. Here the setter is not called, hence it prints stuff
and not my awesome stuff
. The setter would get called only if you use
myCourse.title = "stuff"
If you want the setter to be called on initialization, you need to set the value of title
in an init
block as below
class Course(val id: Int, title: String, var duree: Int, var state: Boolean) {
var title: String = title
set(value) {
field = "my awesome $value"
}
init {
this.title = title
}
}
Or, you can drop the custom setter and set the value of title
with your custom value in the init
block itself
class Course(val id: Int, var title: String, var duree: Int, var state: Boolean) {
init {
this.title = "my awesome ${this.title}"
}
}
Upvotes: 4
Reputation: 1906
I was able to get you example working applying a little change in your code:
class Course (val id:Int, __title:String, var duree:Int, var state:Boolean){
var title:String = ""
get() { return field}
set(value){field = "my awesome" + value}
init {
title = __title
}
}
The difference seems to be the explicit assignment title = __title
, that forces the usage of the custom setter...
Upvotes: 1
Reputation: 93609
The custom setter is only used when you explicitly set the value. The custom setter is not used when you initialize the backing field at the declaration site using = title
.
If you want the custom setter to be applied using the initial value, you can add an init
block to your class:
init {
this.title = title
}
Upvotes: 1