Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - can i use an extension for method overloading?

Tags:

android

kotlin

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 ?

like image 462
j2emanue Avatar asked Nov 03 '25 09:11

j2emanue


1 Answers

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.

like image 160
s1m0nw1 Avatar answered Nov 06 '25 02:11

s1m0nw1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!