Extend data class in Kotlin


Data class is a class that holds the data for an application. It is just like a POJO class that we use in Java in order to hold the data.

In Java, for data class, we need to create getter and setter methods in order to access the properties of that class. In Kotlin, when a class is declared as a data class, the compiler automatically creates some supporting methods required to access the member variable of the class. The compiler will create getters and setters for the constructor parameters, hashCode(), equals(), toString(), copy().

For a class to be considered as a data class in Kotlin, the following conditions are to be fulfilled −

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

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

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

We cannot extend a data class but in order to implement the same feature, we can declare a super class and override the properties in a sub-class.

Example

In the following example, we will create two data classes "Student" and "Book". We will also create an abstract class "Resource". Inside "Book", we will override the properties of the "Resource" class.

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

fun main(args: Array) {
   val stu = Student("Student1", 29)
   val stu2 = Student("Student2", 30)
   println("Student1 Name is: ${stu.name}")
   println("Student1 Age is: ${stu.age}")
   println("Student2 Name is: ${stu2.name}")
   println("Student2 Age is: ${stu2.age}")
   val b=Book(1L,"India","123222") // implementing abstract class
   println(b.location)
}

// declaring super class
abstract class Resource {
   abstract var id: Long
   abstract var location: String
}

// override the properties of the Resource class
data class Book (
   override var id: Long = 0,
   override var location: String = "",
   var isbn: String
) : Resource()

Output

It will generate the following output −

Student1 Name is: Student1
Student1 Age is: 29
Student2 Name is: Student2
Student2 Age is: 30
India

Updated on: 27-Oct-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements