Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to organize Kotlin extension methods

Let's say I have a few extension methods for "MyClass". My question is, what's the best practice to organize/store these methods? Should they be simply put into a "MyClassExtensions" Kotlin file?

I have tried to encapsulate these methods within a class, but after importing the class I couldn't seem to figure out how to use/access the extension methods.

Edit: For clarification, I was not asking for help what to call a file that contains extension methods. I was asking about best practices/approaches to store/organize such methods. Ie. should they be simply put into kotlin files, or should they be encapsulated in a class. I am coming from a Java background, so I'm used to store stuff in classes.

like image 313
pjozsef Avatar asked Mar 25 '16 22:03

pjozsef


People also ask

Where do I put Kotlin extension function?

Actually, it doesn't matter to where you writing them. The extension function are mapped with a class which is already a part of your application. So, it's up to you in which you are going write you extension functions.

What is extension method Kotlin?

Extension functions are a cool Kotlin feature that help you develop Android apps. They provide the ability to add new functionality to classes without having to inherit from them or to use design patterns like Decorator.

Which of the following extension method are used in Kotlin?

Kotlin extension function provides a facility to "add" methods to class without inheriting a class or using any type of design pattern. The created extension functions are used as a regular function inside that class. The extension function is declared with a prefix receiver type with method name.

How Kotlin extension function works internally?

The kotlin extension function is one of the mechanisms that can be provided to extend the class with new functionality without inheriting from the other classes like parent and child classes other design patterns are able to call the classes and their attributes so that their methods make it available for calling the ...


1 Answers

As far as I am concerned, you should put them into a utility file, as you did in Java code base before.

But mention, you no longer need to put them into a class. Top-level functions are the best choice.

You can refer to the kotlin standard library or some open source projects like anko, those would be good examples.

In my case, I put extensions of one class into a file which have the same name of the original file in another package, and use

@JvmMultifileClass 

to reduce the number of generated class files.

like image 128
ice1000 Avatar answered Sep 18 '22 13:09

ice1000