hey everyone. I’ve got a question regarding functi...
# getting-started
o
hey everyone. I’ve got a question regarding functions in companion objects and the best practices around those. I have code:
Copy code
data class Context(
    val fieldArguments: Map<String, Any>,
    val selectionSet: SelectionSet?,
) {
    companion object {
        fun fromEnv(env: Env): Context {
            return Context(
                fieldArguments = env.arguments,
                selectionSet = env.selectionSet,
            )
        }

        fun getEmptyInstance(): Context {
            return Context(
                fieldArguments = emptyMap(),
                selectionSet = null,
            )
        }
    }
}
which I’m not sure I like due to the functions on companion object. on the other hand I could implement something like this, using top-level functions:
Copy code
data class Context(
    val fieldArguments: Map<String, Any>,
    val selectionSet: SelectionSet?,
)

fun createContext(
    env: Env
): BatchLoaderKeyContext {
    return Context(
        fieldArguments = dataFetchingEnvironment.arguments,
        selectionSet = dataFetchingEnvironment.selectionSet
    )
}

fun emptyContext(): Context {
    return Context(
        fieldArguments = emptyMap(),
        selectionSet = null
    )
}
which example would be more Kotlin way? thanks in advance!
r
k
Either way is fine. It has been done both ways in the Kotlin library: • Using companion object: LocalDate.parse • Using top-level function: listOf Use whichever style would be most readable in your callers.
d
Often times, I'll either use secondary constructors, or an
operator fun invoke
on companion object if the initialization I want can't be one via constructor, but I want it to look like a constructor. Sometimes I'll do
fun fromFoo
and the like, if the intent is a lot clearer. Top level functions are also okay, though it depends on the size of the namespace and other things.