Hi, how could we make this function work like a delegate property? ```fun TextView.drawableStart(dra...
s
Hi, how could we make this function work like a delegate property?
Copy code
fun TextView.drawableStart(drawableRes: Int) {
    val drawable = ContextCompat.getDrawable(context, drawableRes)
    drawable?.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
    setCompoundDrawables(drawable, null, null, null)
}
I want to do something like:
Copy code
someTextview.drawableStart = R.drawable.someDrawable
g
do you mean: var TextView.someDrawable: Int set(drawableRes: Int) { … }
👍 1
I just don’t see any delegation here, just standard extension property
s
cool that's what I was looking for!
Copy code
var TextView.drawableStart: Int
    set(drawableRes: Int)  {
        val drawable = ContextCompat.getDrawable(context, drawableRes)
        drawable?.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
        setCompoundDrawables(drawable, null, null, null)
    }
    get() {
        throw Error("Drawable Start Not available")
    }
It works but It must be a var and have a getter to work
g
Correct, it was a typo in my example, it cannot be val of course, if you need setter
You need getter with Int, you can do this: var drawableStart: Int = -1 set(value) { field = value }
Not perfect, because it will have getter value only after first set, but imo better than exception
s
Copy code
Initializer is not allowed here because this property has no backing field
g
Still, function looks a bit more semantically correct for this case
s
It doesn't work here
It doesn't let me have an initializer
probably because it's an extension on TextView
g
Should work
s
no, try it
g
On phone
s
it's ok as is
thanks for the help
g
Ahhhh
Sorry, you right, of course, it's extension
You can implement it by saving value to TV tags if want to make getter work
So no backing field, but getter will read from tags
Again, more like a workaround, it's not perfect because cannot get value before first initialization (same with backing field)
s
using tags for the getter is an idea... but for now I just need the setter, just to make reading the code easier.
*getter
g
If you have a setter, you need a getter for property, this how properties work in Kotlin Personally I would just use extension function for this case, because it's impossible to implement getter correctly, just to avoid possible confusion
s
yes you are correct
145 Views