Search code examples
propertieskotlingetterdelegated-properties

Can't use custom getter with delegated property


I am new to kotlin and can't figure out this issue.

I have a property that is not nullable and may or may not be used. Hence I have delegated it in a lazy way so that it is initialized when required.

private val labelAnimator: ObjectAnimator by lazy {
    ObjectAnimator.ofFloat(this, "floatingLabelFraction", 0f, 1f)
}

However, I also need to set some property of that object every time it is accessed.

fun getLabelAnimator(): ObjectAnimator {
    labelAnimator.duration = (if (isFloatingLabelAnimating) 300 else 0).toLong()
    return labelAnimator
}

But I cannot use a custom getter since the property is delegated. How do I achieve this in best possible way?


Solution

  • You could for example use your original property as Backing Property and actually define the property as a delegation to it.

    private val _labelAnimator by lazy {
        ObjectAnimator.ofFloat(this, "floatingLabelFraction", 0f, 1f)
    }
    
    val labelAnimator: ObjectAnimator
        get() {
            _labelAnimator.duration = if (isFloatingLabelAnimating) 300L else 0L
            return _labelAnimator
        }
    

    This gives you a getLabelAnimator() method in Java and direct property access in Kotlin.

    But like it was stated several times before, it might not be the best way to implement such behavior. A simple factory could do the same with little overhead.