Kotlin Basics - Companion Object

Kotlin Basics - Companion Object

fun main(){
    println(Car.getInfo())
}

class Car(){

    companion object{
        fun getInfo() : String {
            return "Mahindra XUV 300"
        }
    }

}

As observed from the above example,

  • Members of companion object can be called simply by using the class name as a qualifier

  • function inside companion object are called class variables or class functions because they don't belong to a specific object that you create with that class

  • companion objects look like static members in other languages but in run time those are still instance members of real objects

  • the members of companion object can be generated as real static methods or variables if you use the @ JVMStatic annotation

Please leave your comments to improve.

Enjoy and Happy coding