I'm trying to set an extension function on a mutable property so I can reassign the property in the extension function. I wanted to know if it was possible.
My goals is to make Date
extensions for easy access. For example:
fun Date.addDays(nrOfDays: Int): Date {
val cal = Calendar.getInstance()
cal.time = this
cal.add(Calendar.DAY_OF_YEAR, nrOfDays)
return cal.time
}
This function adds number of days to a date using a Calendar
object. The problem is each time I have to return a new date which can be confusing to reassign each time you use this function.
What I've tried:
fun KMutableProperty0<Date>.addDays(nrOfDays: Int) {
val cal = Calendar.getInstance()
cal.time = this.get()
cal.add(Calendar.DAY_OF_YEAR, nrOfDays)
this.set(cal.time)
}
Unfortunately this can't be used on a Date
object.
Is it possible to do this?