properties - Kotlin extension function on mutable property -
i'm trying set extension function on mutable property can reassign property in extension function. wanted know if possible.
my goals make date
extensions easy access. example:
fun date.adddays(nrofdays: int): date { val cal = calendar.getinstance() cal.time = cal.add(calendar.day_of_year, nrofdays) return cal.time }
this function adds number of days date using calendar
object. problem each time have return new date can confusing reassign each time use 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 can't used on date
object.
is possible this?
unfortunately, cannot define extension on member property , call fluently in kotlin 1.0.3.
your extension can rewritten work this:
fun <t> kmutableproperty1<t, date>.adddays(receiver: t, nrofdays: int) { val cal = calendar.getinstance() cal.time = this.get(receiver) cal.add(calendar.day_of_year, nrofdays) this.set(receiver, cal.time) }
with following usage:
class c(var date: date) { ... } val c = c(somedate()) c::date.adddays(c, 123)
with bound callable references (likely supported in kotlin 1.1) possible following syntax:
c::date.adddays(123)
as @marcinkoziĆski suggests, can mutate date
objects without reassigning property:
fun date.adddays(nrofdays: int) { val cal = calendar.getinstance() cal.time = cal.add(calendar.day_of_year, nrofdays) this.time = cal.timeinmillis }
with usage:
class c(var date: date) val c = c(somedate()) c.date.adddays(123)
with solution, have control references date
object mutated. solution works mutable objects, though not suitable property storing immutable ones.
Comments
Post a Comment