33

In Java, it is simple: file name for a type is the name of a type plus .java suffix.

In Kotlin, you can write files that don't contain classes. Is there any convention to name them?

And also how would you name unit test classes for those functions?

gvlasov
  • 18,638
  • 21
  • 74
  • 110

4 Answers4

27

StringExt.kt for the file with extension functions of String.

CollectionExt.kt for Collections extension functions.

WangJie
  • 526
  • 3
  • 7
18

I like WangJie's suggestion of adding a Ext suffix to the filename to communicate that it's a file which contains extensions. (Personally I'd add Extensions instead of Ext but in principle it's the same as what WangJie is suggesting.)

I see by browsing the files in the Kotlin library however that there's a bit of a convention of pluralising the name of the class or type of class for which extensions are being added, e.g. Arrays.kt, Collections.kt, Maps.kt, MutableCollections.kt, Strings.kt. The Source file names section of the Coding conventions document also alludes to this.

Adil Hussain
  • 30,049
  • 21
  • 112
  • 147
11

As for a file with just extension functions, based on the Source files organization section in the docs, you should not create files like this:

Avoid creating files just to hold all extensions of some class.

Instead you should either put the extensions with the class they extend or in the client of them. I personally think this guideline overlooks a pretty fundamental use case: extension functions for classes not owned by you with multiple clients. Also extension functions that have dependencies on classes you don't want to introduce in the module where the extended class is.

In this case it might be good to give a meaningful name instead of FooExt.kt (if all these extension functions have a common purpose). If they don't, it might not make sense to keep them all in the same file. I'm referring to the Source file names guideline where it states:

If a file contains multiple classes, or only top-level declarations, choose a name describing what the file contains, and name the file accordingly.

Adil Hussain
  • 30,049
  • 21
  • 112
  • 147
Yoel Gluschnaider
  • 1,785
  • 1
  • 16
  • 20
1

My approach to this is to put all the extension methods into a package named extensions and the methods into files that are named according to the class they extend, like Int.kt or String.kt.

dStulle
  • 609
  • 5
  • 24