Hi. What are the Kotlin coding conventions for th...
# codingconventions
t
Hi. What are the Kotlin coding conventions for the ordering of public and private functions in the file? I see this in the Kotlin Coding Conventions about ordering when implementing an interface. Does the same then apply when not implementing an interface? https://kotlinlang.org/docs/coding-conventions.html#interface-implementation-layout
Copy code
When implementing an interface, keep the implementing members in the same order as members of the interface (if necessary, interspersed with additional private methods used for the implementation).
Is it 1️⃣ interspersed or 2️⃣ all public first? Something else? And does anyone have ktlint or detekt rules to enforce function ordering? 1️⃣ interspersed
Copy code
class MyClass {
    // Constants or properties

    private val privateProperty: String = "Private"

    // Constructors

    constructor() {
        // Constructor implementation
    }
    
    // Interspersed

    fun publicFunction1() {
       privateFunction1()
    }
    
    private fun privateFunction1() {
        // Private function implementation
    }

    fun publicFunction2() {
        privateFunction1()
    }
    
    private fun privateFunction2() {
        // Private function implementation
    }

    // Companion object

    companion object {
        // Companion object members
    }

    // Overridden functions

    override fun toString(): String {
        // Overridden function implementation
    }
}
2️⃣ all public first
Copy code
class MyClass {
    // Constants or properties

    private val privateProperty: String = "Private"

    // Constructors

    constructor() {
        // Constructor implementation
    }

    // Public functions

    fun publicFunction() {
        // Public function implementation
    }

    // Private functions

    private fun privateFunction() {
        // Private function implementation
    }

    // Companion object

    companion object {
        // Companion object members
    }

    // Overridden functions

    override fun toString(): String {
        // Overridden function implementation
    }
}
2️⃣ 2
🧵 1
1️⃣ 8
z
Code that belongs together should be as close as possible, so interspersed.
👍 1
s
The relevant section of the code style guide is actually just before the section you referenced. “Do not sort the method declarations alphabetically or by visibility […]. Instead, put related stuff together.” https://kotlinlang.org/docs/coding-conventions.html#class-layout
👍 1