Abstract data class kotlin

Kotlin — Data Classes

In this chapter, we will learn about Kotlin Data Classes. A Kotlin Data Class is used to hold the data only and it does not provide any other functionality apart from holding data.

There are following conditions for a Kotlin class to be defined as a Data Class:

  • 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.
  • The class may extend other classes or implement interfaces. If you are using Kotlin version before 1.1, the class can only implement interfaces.

Syntax

It’s simple to define a Kotlin Data Class. If a Kotlin class is marked with data keyword then it becomes a data class. For example:

data class Book(val name: String, val publisher: String, var reviewScore: Int)

Good thing about Kotlin Data Class is that when you declare a Kotlin Data Class, the compiler generates Constructor, toString(), equals(), hashCode(), and additional copy() and componentN() functions automatically.

Example

A Kotlin Data Class is instantiated the same way as other Kotlin classes:

data class Book(val name: String, val publisher: String, var reviewScore: Int) fun main(args: Array) < val book = Book("Kotlin", "Tutorials Point", 10) println("Name = $") println("Publisher = $") println("Score = $") >

When you run the above Kotlin program, it will generate the following output:

Name = Kotlin Publisher = Tutorials Point Score = 10

Copy Function

The copy() function is created automatically when we define a Kotlin Data Class. This copy function can be used to copy an object altering some of its properties but keeping the rest unchanged. Following is an example:

data class Book(val name: String, val publisher: String, var reviewScore: Int) fun main(args: Array) < val original = Book("Kotlin", "Tutorials Point", 10) val copied = original.copy(reviewScore=5) println("Original Book") println("Name = $") println("Publisher = $") println("Score = $") println("Copied Book") println("Name = $") println("Publisher = $") println("Score = $") >

When you run the above Kotlin program, it will generate the following output:

Original Book Name = Kotlin Publisher = Tutorials Point Score = 10 Copied Book Name = Kotlin Publisher = Tutorials Point Score = 5

toString Function

The toString() function is also created automatically when we define a Kotlin Data Class. This function returns a string representation of the object. Following is an example:

data class Book(val name: String, val publisher: String, var reviewScore: Int) fun main(args: Array)

When you run the above Kotlin program, it will generate the following output:

Book(name=Kotlin, publisher=Tutorials Point, reviewScore=10)

hashCode() and equals() Functions

The hasCode()function returns hash code for the object. If two objects are equal, hashCode() returns the same integer value for the objects.

The equals() function returns true if two objects are equal or they have same hasCode value otherwise it returns false.

data class Book(val name: String, val publisher: String, var reviewScore: Int) fun main(args: Array) < val original = Book("Kotlin", "Tutorials Point", 10) val copy1 = original.copy(reviewScore=5) val copy2 = original.copy(reviewScore=7) println("Original Hashcode = $") println("Copy1 Hashcode = $") println("Copy2 Hashcode = $") if( copy1.equals(copy2))< println("Copy1 is equal to Copy2.") >else < println("Copy1 is not equal to Copy2.") >>

When you run the above Kotlin program, it will generate the following output:

Original Hashcode = 1957710662 Copy1 Hashcode = 1957710657 Copy2 Hashcode = 1957710659 Copy1 is not equal to Copy2.

Destructuring Declarations

We can destructure an object into a number of variables using destructing declaration. For example:

data class Book(val name: String, val publisher: String, var reviewScore: Int) fun main(args: Array)

When you run the above Kotlin program, it will generate the following output:

Name = Kotlin Publisher = Tutorials Point Score = 10

Quiz Time (Interview & Exams Preparation)

Q 1 — What is the purpose of Data Classes in Kotlin :

Answer : A

Explanation

Kotlin Data Classes are defined to hold the data only.

Q 2 — Which function is not created by default when we define a Kotlin Data Class

Answer : D

Explanation

All the mentioned functions are created automatically when we define Kotlin Data Class.

Q 2 — What is the function of componentN() in Kotlin Data Class

Answer : C

Explanation

The function componentN() is used to destructure an object into a number of variables.

Источник

Data classes

Data classes in Kotlin are classes whose main purpose is to hold data. Data classes come automatically with additional member functions that allow you to print an instance to readable output, compare instances, copy instances, and more. Data classes are marked with data :

The compiler automatically derives the following members from all properties declared in the primary constructor:

  • .equals() / .hashCode() pair
  • .toString() of the form «User(name=John, age=42)»
  • .componentN() functions corresponding to the properties in their order of declaration.
  • .copy() function (see below).

To ensure consistency and meaningful behavior of the generated code, data classes have to fulfill the following requirements:

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

Additionally, the generation of data class members follows these rules with regard to the members’ inheritance:

  • If there are explicit implementations of equals() , hashCode() , or toString() in the data class body or final implementations in a superclass, then these functions are not generated, and the existing implementations are used.
  • If a supertype has componentN() functions that are open and return compatible types, the corresponding functions are generated for the data class and override those of the supertype. If the functions of the supertype cannot be overridden due to incompatible signatures or due to their being final, an error is reported.
  • Providing explicit implementations for the componentN() and copy() functions is not allowed.

Data classes may extend other classes (see Sealed classes for examples).

On the JVM, if the generated class needs to have a parameterless constructor, default values for the properties have to be specified (see Constructors).

Properties declared in the class body

The compiler only uses the properties defined inside the primary constructor for the automatically generated functions. To exclude a property from the generated implementations, declare it inside the class body:

In this example, only the name property can be used inside the .toString() , .equals() , .hashCode() , and .copy() implementations, and there is only one component function .component1() . The age property can’t be used inside the .toString() , .equals() , .hashCode() , and .copy() implementations because it’s declared inside the class body. If two Person objects have different ages but the same name , then they are treated as equal. This is because the .equals() function can only check for equality of the name property. For example:

Copying

Use the .copy() function to copy an object, allowing you to alter some of its properties while keeping the rest unchanged. The implementation of this function for the User class above would be as follows:

You can then write the following:

Data classes and destructuring declarations

Component functions generated for data classes make it possible to use them in destructuring declarations:

val jane = User(«Jane», 35) val (name, age) = jane println(«$name, $age years of age») // Jane, 35 years of age

Standard data classes

The standard library provides the Pair and Triple classes. In most cases, though, named data classes are a better design choice because they make the code easier to read by providing meaningful names for the properties.

Источник

Читайте также:  Php массив удаление элемента
Оцените статью