Kotlin data classes and sealed classes

Kotlin data classes and sealed classes


data class

Kotlin can create a class that only contains data, with the keyword data :

data classUser(val name:String, val age:Int)   

The compiler automatically extracts the following functions from the primary constructor based on all declared properties:

  • equals()/hashCode()
  • toString()format like"User(name=John, age=42)"
  • componentN() functionsCorresponds to properties, in declaration order
  • copy()function

If these functions are already explicitly defined in the class, or inherited from a superclass, they will no longer be generated.

In order to ensure the consistency and meaning of the generated code, the data class needs to meet the following conditions:

  • The primary constructor contains at least one parameter.

  • All primary constructor parameters must be identified as valor var;

  • A data class cannot be declared as abstract, open, sealedor inner;

  • Data classes cannot inherit from other classes (but can implement interfaces).

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

copy

Copy Using the copy() function, we can use this function to copy the object and modify some properties. For the User class above, its implementation will look like this:

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

example

Use the copy class to copy the User data class and modify the age attribute:

data classUser(val name:String, val age:Int)   


fun main(args:Array<String>){
    val jack =User(name ="Jack", age =1)
    val olderJack = jack.copy(age =2)
    println(jack)
    println(olderJack)      

}

The output is:

User(name=Jack, age=1)User(name=Jack, age=2)

Data classes and destructuring declarations

Component functions allow data classes to be used in destructuring declarations:

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

standard data class

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.


Sealed

Sealed classes are used to represent a restricted class inheritance structure: when a value is of a limited number of types and cannot have any other type. In a sense, they are extensions of enum classes: the set of values ​​of enum types is also limited, but only one instance of each enum constant exists, while a subclass of a sealed class can have many states that can be contained. instance.

Declare a sealed class and use sealed to decorate the class. The sealed class can have subclasses, but all subclasses must be embedded in the sealed class.

sealed cannot modify interface, abstract class (warning will be reported, but no compilation error will occur)

sealedclassExpr
data classConst(val number:Double):Expr()
data classSum(val e1:Expr, val e2:Expr):Expr()objectNotANumber:Expr()           
   

fun eval(expr:Expr):Double=when(expr){isConst-> expr.number
    isSum->eval(expr.e1)+eval(expr.e2)NotANumber->Double.NaN}      
           
      

The key benefit of using sealed classes is that when using when expressions, if you can verify that the statement covers all cases, you don't need to add an else clause to the statement.

fun eval ( expr : Expr ): Double = when ( expr ) { is Expr . Const -> expr . number
     is Expr . Sum -> eval ( expr . e1 ) + eval ( expr . e2 ) Expr . NotANumber -> Double . NaN // `else` clause is no longer needed because we have covered all cases }     
           
      
    

Reprinted from: http://www.runoob.com/kotlin/kotlin-data-sealed-classes.html

Guess you like

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