data class

data class

We often create a class that just holds data. Some functions in such classes just mechanically perform some derivation
on the . Such classes in kotlin are called data classes and are annotated with data:

data class User(val name: String, val age: Int)

The compiler will automatically add the following methods based on all properties declared in the primary constructor:
- equals() / hashCode functions
- toString format is "User(name=john, age=42)"
- [componentN()functions] ( http: //kotlinlang.org/docs/reference/multi-
- declarations.html) corresponds to all properties in declaration order
- copy() function

If these methods are explicitly declared in the class or inherited from the base class, the compiler will not generate them automatically.

To ensure the consistency of these generated codes and achieve meaningful behavior, data classes must meet the following requirements:

Note that if there is no val or var in the constructor parameters, it will not appear in these functions;

  • The primary constructor should have at least one parameter;
  • All parameters of the primary constructor must be marked as val or var;
  • The data class cannot be abstract, open, sealed, or inner;
  • Data classes cannot inherit from other classes (but can implement interfaces).
  • In the JVM if the constructor is parameterless, all properties must have default values ​​(see
  • see Constructors);
  • data class User(val name: String = “”, val age: Int = 0)

copy

We often make changes to some properties but want others to remain the same. This is where the copy() function
comes in . In the User class above, the implementation should look like this:

fun copy(name: String = this.name, age: Int = this.age) = User(n
ame, age)

With copy we can write like this:

val jack = User(name = "jack", age = 1)
val olderJack = jack.copy(age = 2)

Data classes and multiple declarations
Component functions allow data classes to be used in multiple 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 Pair and Triple. In most cases, named data classes are a better design
choice because the code is more readable and provides meaningful names and properties

Guess you like

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