Pandiyan Mani
1 min readAug 19, 2021

--

Companion Object and Data class

what is Companion Object?

If you want to acccess any particular variable or method from a class with out intializing the class object we can call directly by using the class name followed by variable or method name it is similar to static in java

class sample
{
companion object
{
var a:Int =5
}
}

and we can call directly by using class name from our main class

println("--->"+sample.a)

what is Data class?

Data class which holds the data.When we mark a class as a data class, you don’t have to implement or create the following functions as we do in Java

hashCode()

equals()

toString()

copy()

Although, there are few requirements that data classes need to fulfill:

1.The primary constructor needs to have at least one parameter.

2.All primary constructor parameters need to be marked as val or var

3.Data classes cannot be abstract, open, sealed, or inner.

--

--