kotlincompanion-objectextension-function

Kotlin : function extension inside companion object


In Kotlin language, what does this syntax do and how does it work ?

class ClassName1 {
    companion object {          
        fun ClassName2.funName()=""         
    } 
}

Solution

  • There are multiple things at play here:

    Declaring a member extension function inside a companion object might be useful for different things.

    For instance, such function can be used within the class as if the extension function was declared as a class member but outside the companion. Some people prefer to put them in the companion object to make it clear that they don't depend on the state of said class (like a Java static function):

    class ClassName1 {
    
        fun method(): String {
            val something = ClassName2()
            return something.funName()
        }
    
        companion object {          
            fun ClassName2.funName() = ""         
        } 
    }
    

    Such use doesn't require the function to be public, though.

    Another way to use this would be by using the companion object as a sort of scope:

    val something = ClassName2()
    with(ClassName1) { // this: ClassName1.Companion
       something.funName() // brought in scope by ClassName1's companion
    }
    

    Or directly if you import the function from the companion:

    import ClassName1.Companion.funName
    
    val something = ClassName2()
    something.funName()
    

    Such pattern is used for instance for Duration.Compaion to define extensions on number types (those are extension properties but it's the same idea): https://github.com/JetBrains/kotlin/blob/6a670dc5f38fc73eb01d754d8f7c158ae0176ceb/libraries/stdlib/src/kotlin/time/Duration.kt#L71