Moving to Kotlin - data classes and enclosing classes

Data classes and closed classes are two special classes in Kotlin, let’s take a look at them today. For more exciting content, you can also pay attention to my WeChat public account - Android Motor Vehicles

data class

Data classes are a syntactic sugar for Kotlin. The Kotlin compiler will automatically generate some member functions for data classes to improve development efficiency.

Use of data classes

Whether it is Java server development or Android development, the entity class is naturally very familiar. It is to convert the json format into an entity class that only contains data and basic operation methods to facilitate network access and database access.

We always need a class to represent data. For example, to represent the data of a user, we will create a User class and pass in two properties through the constructor:

class User(name: String, age: Int) {
    var mName = name
    var mAge: Int = age
}

We define an entity class. In addition to saving data, we also need to output the value of the object, compare objects and other operations. The former will use the toString function, and the latter will use the equals function, as follows:

var user1 = User("js", 20)
var user2 = User("lx", 12)

println(user1)
println(user2)
println(user1.equals(user2))

The output is:

User@3764951d
User@4b1210ee
false

It can be seen from the results that when outputting the two objects of User, the toString method of the two objects is called, but the toString function will call the hashcode function by default, output the hashcode of the current object, and add the class .

The equals method of the object also compares the hashcodes of the two objects by default. If the hashcodes of the two objects are different, it naturally returns false.

Sometimes our business requirements are as follows: to print an object, that is, to print all the properties of the object according to the rules, if all the properties of the two objects have the same value, then the two objects are returned equal, so we need to rewrite the toString function and the equals function, I believe Everyone can write, so I won't be too cumbersome here.

Although the User class written above achieves our needs, it will be too troublesome. Each class needs to override methods such as toString and equals. In order to improve development efficiency, Kotlin has added the data classes we will introduce soon.

The so-called data class is to define only the necessary parts, and the rest can be automatically generated.

As can be seen from the above class, only name and age are required, and the rest can be automatically deduced. Data class rules: Attributes must be specified through the primary constructor, and data must be added before the class keyword. Let's write another data class as follows:

data class Person(var name: String, val age: Int)

It can be seen that the original code of dozens of lines and dozens of lines is now completed in one line, and the rest of the Kotlin compiler will be automatically generated.

Data classes, like ordinary classes, can also inherit from other classes and have some other member functions.

Writing a data class requires attention:

  • The primary constructor must have at least one parameter;
  • The parameters of the primary constructor should be modified with var or val;
  • A data class cannot be an abstract class, an open class, a closed class, or an inner class.

Since there must be at least one parameter in the primary constructor, it is impossible to have a primary constructor without parameters in a data class. To make a data class UF a constructor without parameters, there are the following two methods:

  1. Add a default value to each parameter of the main constructor;
  2. Add a secondary constructor with no parameters, and call the primary constructor while specifying the parameters.
data class MPerson(var name: String = "js", var age: Int = 20)

data class NPerson(var name: String, var age: Int) {
    // 次构造器,this调用猪狗早起,并指定参数
    constructor() : this("js", 20)
}

object copy

In development, we often need to copy an object and then modify some of its properties, which requires a copy mechanism. In addition to automatically generating the toString method and the equals method for data classes, Kotlin also generates a copy method by default. Its function is to Copy an instance of the data class. code show as below:

var person = Person("wj", 20)
var mCopyPerson1 = person.copy()
var mCopyPerson2 = person.copy(name = "js")

Destructuring of data class members

The so-called destructuring is to deconstruct, which refers to extracting the attributes in the data object and assigning them to a single variable.

The Kotlin compiler will automatically generate component functions for the data class (which will be discussed later), hidden, and you can directly deconstruct the data class members:

var js = Person("Js", 20)
// 将js.name和js.age分别赋给name和age变量
var (name, age) = js
println("$name, is $age years old")

closed class

Enclosing classes can be seen as extensions of enums. A closed class, previously identified with the sealed keyword. Someone can have multiple subclasses and objects. The values ​​of the enclosing class can only be these subclasses and objects.

The advantage of using a closed class is that the when expression does not need to use the else form. See an example:

sealed class Expr

data class Const(var count: Int) : Expr()
data class Sun(var e1: Expr, var e2: Expr) : Expr()

fun evel(expr: Expr): Int = when (expr) {
    is Const -> expr.count
    is Sun -> evel(expr.e1) + evel(expr.e2)
}

Summarize

Some special classes are provided in Kotlin, of which data classes and enclosing classes are two of them. Although these special classes are not necessary, sometimes using them will bring great convenience to our development, especially the data classes.

For more exciting content, please pay attention to my WeChat public account - Android Motor Vehicles

write picture description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325553898&siteId=291194637