4

I have created a custom view in android. one of the methods has a signature like this:

fun show(CategoryFilterModel model) {/*...*/}

and it works fine. and now i'd like to create a overloaded function which would look like this if i did it by adding it to the custom view class:

fun show(ShopFilterModel model) {/*...*/}

Notice the type is different so this is a method overload.

a thought came to me that i could instead use an extension in kotlin to add another method to the class.

so it would like something like this:

fun MyCustomView.show(ShopFilterModel: model){

    }

is this advised or should i only add utility methods with extensions ? Are there any overheads ?

j2emanue
  • 60,549
  • 65
  • 286
  • 456
  • It will compile into a `static show(MyCustomView self, ShopFilterModel model)`. Runtime overheads, if any, will be very small. – Marko Topolnik Jan 17 '18 at 07:34
  • sense it will compile into a static how can i reference object variables, i assume i cannot then, correct ? – j2emanue Jan 17 '18 at 07:35
  • It has the `self` argument, this is the instance holding the variables. But you can't access any `private` members and this could be a show-stopper. – Marko Topolnik Jan 17 '18 at 07:38
  • There's a pitfall with extension funs and overloading: if the member's signature is compatible with your extension fun's, but more general, it will get selected before even considering yours. – Marko Topolnik Jan 17 '18 at 12:32
  • very good point to know some of the drawbacks. thanks – j2emanue Jan 17 '18 at 13:04

1 Answers1

4

It’s not only for utilities, as you can read in this great answer, which lists pretty much all use cases.

Imho, if you have control over that class you want to extend with a method, there’s no problem to add the method directly to it as opposed to doing it with an extension method. Yet, technically you can consider doing this. Please be aware that calling such an extension function from Java isn’t very idiomatic because it will be compiled to a static function. If it’s ever going to be invoked from Java, I’d rather use ordinary methods when possible.

s1m0nw1
  • 76,759
  • 17
  • 167
  • 196