Language Elements

Data Types

Kotlin Nullable Types

Exctension Functions

Lambda Functions

Object Oriented Kotlin

Data Classes

Collections

Kotlin Example Codes

Kotlin Interview Questions

In comparison to Java, Kotlin provides a simpler way to declare data classes with much less boilerplate code, eliminating the need to manually add getters and setters (these are automatically generated by the compiler). The keyword data is used to define a data class. Using this keyword, the compiler identifies a data class and generates standard functions such as equals(), hashCode(), toString(), copy(), and componentN() functions for property access. To define a data class, you simply specify the property names, their types, and optional initial values in the primary constructor.

Requirements for a Kotlin Data Class:



Example of a Kotlin Data Class:

data class Employer(val companyName: String, val marketValueInBillions: Int)

fun main() {
    val employer = Employer("TechCorp", 4)
    println("Company Name: ${employer.companyName}")
    println("Market Value (in billions): ${employer.marketValueInBillions}")
}

In the above example: - The Employer class is declared as a data class. - The primary constructor defines two properties: companyName and marketValueInBillions. - When an instance of the Employer class is created, the compiler automatically provides implementations for the standard functions. This approach enhances code readability and reduces boilerplate, making Kotlin particularly well-suited for data modeling.


Copyright © by Zafar Yasin. All rights reserved.