Language Elements

Data Types

Exctension Functions

Object Oriented Kotlin

Data Classes

Coroutines

Collections

Kotlin Example Codes

Kotlin Interview Questions

comparison to Java, Kotlin provides a simple way to declare data classes, with much less boiler plate code, without any need of adding getter and setter (generated by the compiler). The key word data is used to create a data class. From this key word, Compiler identifies a data class, and then create functions to manage it. To define a data class, one needs list of property names, types and optional initial values.

Kotlin Data class requirements:

  • The primary constructor must have at least one parameter, marked as val or var.

  • The class cannot be marked as open, abstract, sealed or inner.

  • The class may extend other classes or implement interfaces.


  • Example of Kotlin Data Class
    
    data class Employer(val companyName: String, val marketValueInBillions: Int)
    
    
    fun main() {
        val s1 = Employer("abcd", 4)
        println("companyName= ${s1.companyName}")
        println("marketValueInBillions = ${s1.marketValueInBillions}")
    }
    
    
    
    data class Person(val name: String, val age: Int)
    
    
    fun main() {
       
       // PersonName for any name string
    val person = Person("PersonName", 35)
    println(person)
    
    }
    
    



    Copyright © by Zafar Yasin. All rights reserved.