Sudhir Singh Khanger
08/08/2020, 11:11 AMprivate val someTopLevelFunction = SomeClass.Builder().build()
object SomeObject { val someObjectVariable by lazy { someTopLevelFunction().someMethod(someParam) } }
The other option is to use companion object.
interface SomeInterface {
companion object {
fun someTopLevelFunction() = SomeClass.Builder().build()
}
}
These would be called as SomeObject.someObjectVariable()
and SomeInterface.someTopLevelFunction()
. As far as I understand top-level functions they can be accessed directly from anywhere which may pollute auto-completion. But if they are private then that issue won't happen. At the same time, I am not clear what would be their advantage if they are declared as private. Which one would you prefer? And why?nanodeath
08/08/2020, 2:17 PMsomeTopLevelFunction
is different (and btw, not a function in the first case).
Basically, do things outside the file need to call someTopLevelFunction
or no?
Top-level functions and vals do pollute the namespace a bit, but you're free to use package namespaces more liberally in Kotlin than you might in Java, which mitigates the issue, since you have to explicitly import top-level things if they're in a different package.Sudhir Singh Khanger
08/08/2020, 2:31 PMsomeTopLevelFunction
is not a function but a variable. It is only accessed directly in the file. Outside file it is accessed lazily using variable someObjectVariable
.nanodeath
08/08/2020, 2:43 PMobject
already is a kind of namespace, and a much better one because you can't write a class that implements it.Sudhir Singh Khanger
08/09/2020, 4:48 PMnanodeath
08/09/2020, 5:31 PM