36
votes

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.

1
Thanks, I must have accidentally missed this part in the docs.pjozsef
best practices/approaches to store/organize such methods that makes this question very opinion basedvoddan

1 Answers

11
votes

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.