1

I'm trying to create an extension function in Kotlin. I did try several tutorials, but didn't quite understand, how to implement this one.

I'm trying to create a setWidth() function as such

//Find my_view in the fragment
val myView = v.findViewById<RelativeLayout>(R.id.my_view)

//Then use the extension function
myView.setNewWidth(500)

This is how I've defined my extension function


private fun View?.setNewWidth(i: Int) {
    val layoutParams: ViewGroup.LayoutParams = View.layoutParams
    layoutParams.width = i
    View.layoutParams = layoutParams
}

I don't understand what I need to do here.

I want to call the extension function as myView.ExtensionFunction(), but I don't know how to do that. The tutorials, were un-informative.

SowingFiber
  • 1,194
  • 1
  • 12
  • 32

2 Answers2

5

I think the main problem here is how the extension function is defined, in particular, the lines that have View.layoutParams - this is calling a static property on View that doesn't exist. You need to use the one from the instance. If you'd write the extension function like so:

private fun View?.setNewWidth(i: Int) {
  val layoutParams = this?.layoutParams
  layoutParams?.width = i
  this?.layoutParams = layoutParams
}

Then you can call the method like you want. Personally, I don't find this so readable and I'd remove the nullability here and write it as:

private fun View.setNewWidth(i: Int) {
  val newLayoutParams = layoutParams
  newLayoutParams?.width = i
  layoutParams = newLayoutParams
}

The only difference is that now you need ?. to call the method if the view is nullable, which I personally find fine - myView?.setNewWidth(123). I assume most of the time you won't have a nullable view.

Fred
  • 16,367
  • 6
  • 50
  • 65
1

Ok, So my issue was that I didn't know how to get reference to the calling View. i.e., I didn't know how to call myView and set its property inside the extension function setNewWidth()

So, I tried using this? and it worked.

Then, I did a few changes to the extension function to work for myView which is a Relative Layout.

This is what I worked out:

private fun RelativeLayout?.setWidth(i: Int) {
    val layoutParams: ViewGroup.LayoutParams? = this?.layoutParams
    layoutParams?.width = i
    this?.layoutParams = layoutParams
}

SowingFiber
  • 1,194
  • 1
  • 12
  • 32
  • It is `this` you use, not `this?`. E.g. you can't write `val view = this?`. `?` here is part of the `?.` safe call operator. – Alexey Romanov Dec 30 '19 at 09:51