We are currently switching our project to Kotlin, and ran across following question:
We need a certain extension function only inside a given class. Thus, we have two possibilities: (1) Declaring the extension function private
on the file top-level or (2) declaring the extension function private
inside the class.
Following a MCVE:
Top-level example (file C1.kt
):
private fun String.double() = this.repeat(2)
class C1 {
init {
println("init".double())
}
}
Inside class example (file C2.kt
):
class C2 {
private fun String.double() = this.repeat(2)
init {
println("init".double())
}
}
Questions:
Is there any difference to those two approaches, except that in
C1.kt
the extension functionString.double()
would also be visible to other possible file members (such as further classes in the same file)?Since we want to achieve code "as kotlinic as possible", we would like to know which of the two approaches is the suggested one. Is there an official suggestion / style guide on the example above? I think it is considered good practice to declare extension functions as close as possible to its intended use, thus in the above example the structure of
C2
would be suggested?