Companion Object In Kotlin

  • In Kotlin, If we want to write a function or member of a class that can be called without having the instance of the class, there comes the role of the companion object.
  • So, by declaring the companion object, you can access the members of the class by name only.
class Utils{
    companion object{
        fun yourFun() = println("Have Fun With Companion Object")
    }
}

fun main() {
    println(Utils.yourFun())
}

You can run it on Kotlin Playground

chevron_left
chevron_right
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x