DEV Community

Sanjay Prajapat
Sanjay Prajapat

Posted on • Edited on • Originally published at sanjayprajapat.hashnode.dev

3 1

Data class in Kotlin

The main purpose of data class is hold data , in koltin compiler automatically creates following

  • getters and setters for the constructor parameters -
  • hashCode()
  • equals()
  • toString()
  • copy()
  • componentN() function

following condition should be fullfilled to create a data class

  • 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.

to exclude a property for generated implementation declare it inside data class

 data class Person(val name:String?=null, val age:Int? = null ){

    var excludeProp:Int = 34

    fun personDetails():String?{
        return "name=$name Age=$age"
    }
 }
Enter fullscreen mode Exit fullscreen mode
fun main(args: Array<String>) {

    // val p1 = Person ()
    var  p1 = Person ("Justin", 27)
    val p2 = Person ("Justin", 27)
    val p3 = Person ("Justin", 26)

    println(p1) // 
    println(p1 == p2) // true 
    println(p1 == p3) // false

    p1.excludeProp = 90
    println(p1.excludeProp) // 90 
    println(p2.excludeProp) // 34 

    // use copy() when want to change some of properties of object , rest properties are unchanged 

    val newPerson = Person("Karl Bruce", 18)
    val oldPerson = newPerson.copy(age = 90)
    println(oldPerson) // Person(name=Karl Bruce, age=90)

    //Data classes and destructuring declarations

    val p5 =  Person("Chris", 45)
    val (name , age ) = p5
    print("name = $name  age =$age") //name = Chris  age =45

    //call function
   print( p5.personDetails() ) // name=Chris Age=45 

}

Enter fullscreen mode Exit fullscreen mode

Sentry mobile image

App store rankings love fast apps - mobile vitals can help you get there

Slow startup times, UI hangs, and frozen frames frustrate users—but they’re also fixable. Mobile Vitals help you measure and understand these performance issues so you can optimize your app’s speed and responsiveness. Learn how to use them to reduce friction and improve user experience.

Read full post →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay