https://kotlinlang.org logo
Title
s

Sudhir Singh Khanger

08/08/2020, 11:11 AM
I came across two sets of code one where top-level-variable and an object is used and one where companion object is used. I am wondering which one is better.
private 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?
n

nanodeath

08/08/2020, 2:17 PM
Not sure these are exactly comparable. The interface isn't even exactly the interesting part here; you just have two objects (one top-level, one as a companion object), and the visibility of
someTopLevelFunction
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.
s

Sudhir Singh Khanger

08/08/2020, 2:31 PM
Sorry I made a mistake there.
someTopLevelFunction
is not a function but a variable. It is only accessed directly in the file. Outside file it is accessed lazily using variable
someObjectVariable
.
n

nanodeath

08/08/2020, 2:43 PM
In that case...it's really just a question of whether your object is inside an interface or top-level. If the interface is literally empty except for the object, then it's not really an interface, it's more of a namespace. and
object
already is a kind of namespace, and a much better one because you can't write a class that implements it.
s

Sudhir Singh Khanger

08/09/2020, 4:48 PM
Interface will contain functions. The interface will be used to initialize the a Retrofit object (a popular Android networking library) and functions in the interface will be called upon that initialized Retrofit object. Question is where to initialize the Retrofit object. 1. In the interface's companion object. 2. In a file as a top-level variable which is initialized lazily in an object. I am mostly trying to understand which style is considered better.
n

nanodeath

08/09/2020, 5:31 PM
right, but it's not really a style question