Updated April 1, 2023
Introduction to Kotlin Data Class
The kotlin data class is one of the types and features for to hold the user input data and state in such cases we use some standard functions for to derive the datas which is enable to ensure consistency, and it is a meaningful behavior for to generate codes, it has the primary constructor which helps and needs to pass have at least one parameter which is all have the primary constructor that needs to be marked as val or var type the data classes cannot be abstract, and it is an open also which is a sealed or inner type.
Syntax of Kotlin Data Class
In kotlin language, we use classes, methods and other pre-defined keywords for to create the mobile-based application. For example, among the Data class is one of the concepts and features for storing and hold the data and state with the help of some standard keywords and methods.
fun main(args:Array<String>)
{
data class classname(val name: datatype, var name1:datatype,…)
------some logics and codes which based on the requirement---
}
The above code is the basic syntax for to utilizing the data class in the main method of the kotlin language. We can pass n number of arguments which helps to call and declare the data class in throughout the package.
How does Data Class work in Kotlin?
The data class is one of the features and concepts for developing the application, which helps to store and hold the data and state in parallely. Comparing class is one of the best, and it is a better solution for avoiding the boiler-plate codes. It also modified the modifier data to the class; it will generate the default methods automatically like toString(), equals() etc. We can mainly use the toString() method to convert the inputs to a string format and check the string inputs and stores in the hash memory. Data class cannot be extended, so it looks and similar to the abstract concept. It contains only the fields and other crud methods while accessing the datas by using the getter and setter methods.
It also looks like simple containers for data which used by other classes, and it does not contain any additional functionality and cannot be handle independently while operate the data that they have been owned. If we want to inherit the data class, we can use an open keyword for to inherit it. The data class is the standard functionality the compiler automatically compiled the functions like equals(), toString() etc., when the data class loads on the compiler. It also separates the primary constructor at least one parameter; it should be either val or var keyword. It only implements with the help of interfaces.
Examples of Kotlin Data Class
Given below are the examples of Kotlin Data Class:
Example #1
Code:
package one;
sealed class Month
data class Date(val a: Int) : Month()
data class Year(val b: Int) : Month()
data class Employee(val name: String, val id: Int)
fun main(args: Array<String>)
{
data class department(val name: String)
{
var empid: Int = 0;
}
val out=department("Research & Development")
out.empid = 41
println(out.toString());
println(out.empid);
println("Welcome To My Domain its the first example that related to the kotlin data class")
val emp = Employee("Sivaraman", 31)
val emp1 = Employee("Siva", 32)
val emp2 = Employee("Raman", 29)
if (emp.equals(emp1) == true)
println("emp is equal to emp1.")
else
println("emp is not equal to emp1.")
if (emp.equals(emp2) == true)
println("emp is equal to emp2.")
else
println("emp is not equal to emp2.")
println("The Hashcode of emp: ${emp.hashCode()}")
println("The Hashcode of emp1: ${emp1.hashCode()}")
println("The Hashcode of emp2: ${emp2.hashCode()}")
val id=emp.component1()
println("The Employee id is: $id")
fun new()
{
val listss:List<Month> = listOf(Date(17),Year(2021), Year(2021))
println("Welcome To My Domain is the first example that related to the Kotlin data class ")
println(listss)
val mapss = HashMap<Int, String>()
mapss.put(1, "siva")
mapss.put(2, "raman")
mapss.put(3, "arun")
mapss.put(4, "kumar")
mapss.put(5, "dhanajay kumar prasad")
mapss.put(6, "arul")
mapss.put(7, "devendran redim kumar tharun")
mapss.put(8, "daisy sran kumar yadav")
mapss.put(9, "Alan nirmal williamson")
mapss.put(10, "varadhaman vishal jain")
println(mapss)
}
}
Output:
In the above example, we used collections with data classes; additionally, we used a basic method like Hash code() etc. For to retrieve the hash reference from memory.
Example #2
Code:
package one;
data class Textile(var name: String, var brandName: String = "Derby", var Quality: Long = 2345, var Qunatity: Int = 10, var cost: Int = 500)
data class User(var name: String, var age: Int)
fun main(args: Array<String>) {
var Textile = Textile("Sivaraman","Derby", 2345, 10, 500)
println(Textile)
Textile = Textile("Welcome To My Domain its the Second Example that related to the Kotlin data class")
println(Textile)
Textile = Textile("Jockey",cost = 800)
println(Textile)
Textile = Textile("Allensolly","DSP",Qunatity = 15, cost = 1200)
println(Textile.toString())
Textile = Textile("Viking","Poomex",Qunatity = 27)
println(Textile.toString())
println("We can copy the data class datas into the separate variable and while calling the copy() function for to store it")
val res = User("Siva", 32)
println(res)
val result = res.copy()
println(result)
}
Output:
In the second example, we used data classes with a pre-defined method like the copy() method to perform the main method’s copy operations.
Example #3
Code:
package one;
import java.io.Serializable
import kotlin.reflect.full.superclasses
sealed class Colors
data class Red(val a: String) : Colors()
data class Green(val b: String) : Colors()
class Test:Serializable{
fun demo()
{
val lst:List<Colors> = listOf(Red("Its the red color image"),Green("Its the Green Color image"))
println("Welcome To My Domain is the third example that related to the Kotlin data class ")
println(lst)
val lst1: List<String> = listOf("Blue", "Yellow", "Violet", "Orange", "Pink")
val arrayres: Array<String> = lst1.toTypedArray()
arrayres.forEach { System.out.print(it) }
val mp = HashMap<Int, String>()
mp.put(1, "first color")
mp.put(2, "second color")
mp.put(3, "third color")
mp.put(4, "fourth color")
mp.put(5, "fifth color")
mp.put(6, "sixth color")
mp.put(7, "seventh color")
mp.put(8, "eigth color")
mp.put(9, "ninth color")
mp.put(10, "tenth color")
println(mp)
}
}
fun main(args: Array<String>) {
val nm= Test()
println(nm.demo())
}
Output:
In the final example, we used collection concepts additionally like map, a list with data classes.
Conclusion
In kotlin, language class is one of the blueprint models, and it can be stored with all the methods and default variables. If we call the specific method in the class, we can create the instance and call the particular method. Here, the data class is somewhat different from the normal class; it cannot be extended and stored the datas/states using default methods.
Recommended Articles
This is a guide to Kotlin Data Class. Here we discuss the introduction, syntax, and working of data class in kotlin along with different examples and code implementation. You may also have a look at the following articles to learn more –