I'm curious how others organize their "extension" ...
# getting-started
t
I'm curious how others organize their "extension" methods/functions. When they're highly specific to just one place, I just put them at the bottom of that file. But if I have a general purpose one that I want to use throughout my project, I've tried different things. I used to put them 1:1 in a <ClassName>_extensions.kt file. More of late, I've just been glumping them by category with a misc prefix (e.g. misc_numerics.ket for any extensions on Float/Double/Int/etc or misc_temporals for all of time/datetime/calendar/etc extensions). Curious what others do
c
Personally: • if there are not many, end of the file • if there are many, another file with the postfix "Ext" (
Foo.kt
FooExt.kt
) • if there are not really anything else in the package, I just name them after what they do (e.g. in this package, there is a sealed class and everything else is just extension functions on it)
👍 2
e
if they're too many to put in the same source file and there's no other sub-grouping, I tend to put them in a
${classname}s.kt
file, e.g.
Floats.kt
for functions on `Float`s
c
I prefer the Intellij file viewer to show the symbol for class/object/etc. so I almost always keep the main class alone in its file and put the extension functions in a separate file. I usually label it with a suffix of
Utils
, because not every function in that file is strictly an “extension function”, and I guess I’m just used to the Java naming convention
t
like the utils idea, thanks
s
if they are very short (1-2 lines) and only used in one function, I put them at the beginning of the function.
1
k
The Kotlin Coding Conventions say:
Copy code
when defining extension functions for a class which are relevant for all clients of this class, put them in the same file with the class itself. When defining extension functions that make sense only for a specific client, put them next to the code of that client. Avoid creating files just to hold all extensions of some class.
This doesn't explain what you should do if you are defining extension functions that are relevant to all clients but they are extensions of a third-party class so you can't put them in with that class. In that case, ephemient's use of the plural of the class name sounds sensible.
👍 2
d
I'm working on some Kotlin friendly extensions to Swing, and I tend to put extension methods related to swing classes in
_ClassName.kt
e
there's no technical issues with using
ClassName.kt
to hold extensions for classes defined in
ClassName.java
stylistically, I think plurals work fine. after all, even Java has
Collections.java
for extra
Collection
functions, etc.