You are here
Home > Kotlin

Kotlin: Companion Object

companion object

Companion Object

In this post we will discuss companion object in kotlin.

  • Kotlin not support static methods and variable so we use companion object to make variable and methods static.
  • The companion objects are declared inside a class using companion
  • The function declared inside a companion object are called using class name and function name.
  • Function and variable declare inside companion objects behave like a static variable and method.
  • When companion object is compile it is converted into statics.
  • It is not necessary to provide a name to companion object.
  • Example:

class Person {
// name of the companion object is omitted
companion object {
var id:Int=21;           //behave like static variable
fun callMe():Unit        //behave like a static method
{
println(“My Name is Riya”)
}
}
}

fun main(args: Array<String>) {
Person.callMe()
println(Person.id);
}

output:

Explanation:

In above example, we create a Person class and inside class create a companion object. It has id variable and function callMe(), when companion object is compile its variables and functions converted in to static. We call the static function using class name.

You can also by SQL 70-761 book write by me from Amazon.
You can also by Kotlin Book write by me from Amazon.

Microsoft SQL 70-762 Practice Test.

Microsoft MCSA 70-761 Practice Test:

Leave a Reply

Top