Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between object and data class in Kotlin?

Tags:

kotlin

What is difference between data and object class in Kotlin, and what is the purpose of each?

data class User(val name: String, val age: Int)

and

object user {
    val name = ""
    fun printName(name: String) = "Hello, $name!"
}
like image 845
Samir Mangroliya Avatar asked Feb 02 '19 14:02

Samir Mangroliya


1 Answers

object

object is Kotlin's way to create a singleton (one instance class) which is instantiated by the compiler.


data class

A data class is like a usual class but with a few advantages/resctrictions (Source).

Advantages

  • equals()/hashCode()
  • toString()
  • componentN()
  • copy()

Those are created from the properties specified in the primary constructor.

Restrictions

  • The primary constructor needs to have at least one parameter;
  • All primary constructor parameters need to be marked as val or var;
  • cannot be abstract, open, sealed or inner;
  • (before 1.1) may only implement interfaces.
like image 128
Willi Mentzel Avatar answered Sep 18 '22 12:09

Willi Mentzel