Search code examples
kotlinidioms

How to idiomatically format .apply{} in Kotlin?


This might seem a little trivial, but since we read more code than we write, I want to know which of these versions looks nicer and more readable for you

private val VALUES by lazy {
    mutableListOf<Value>().apply {
        add(VALUE_1)
        add(VALUE_2)
        add(VALUE_3)
    }
}

OR

private val VALUES by lazy {
    mutableListOf<Value>()
        .apply {
            add(VALUE_1)
            add(VALUE_2)
            add(VALUE_3)
        }
}

In other words, should we care that the method (.apply) be on the same line as the caller, or the ending curly bracket to be aligned with the (.apply) method?


Solution

  • As per https://kotlinlang.org/docs/reference/coding-conventions.html

    Chained call wrapping

    When wrapping chained calls, put the . character or the ?. operator on the next line, with a single indent:

    val anchor = owner
        ?.firstChild!!
        .siblings(forward = true)
        .dropWhile { it is PsiComment || it is PsiWhiteSpace }
    

    The first call in the chain usually should have a line break before it, but it's OK to omit it if the code makes more sense that way.

    So it's up to you :)