Kotlin Series 5 --- data class, seal class, internal class details, kotlin ---

Source: Internet
Author: User

Kotlin Series 5 --- data class, seal class, internal class details, kotlin ---

Summary: kotlin has been learning for a while. It takes a little time to look at it every day. It will take a long time to forget it. It is only necessary to sort it out again, in this article, we will sort out the basic usage of several categories, which are roughly the same as things on the kotlin website.

Data

In java or other languages, for the sake of clear code logic, we will always create classes that only store state attributes or data. These classes are called data classes, in kotlin, in order to make data classes simpler and more standardized, we add our own labels and modifier data to the data classes and have our own rules. Then we create a simple data class:

data class DataClass(var  name : String) {}
To ensure the consistency and meaningful behavior of the generated code, the data class must meet the following requirements:
The primary constructor must have at least one parameter. All parameters of the primary constructor must be marked as val or var. Data classes cannot be abstract, open, sealed, or internal. (before 1.1) data classes can only implement interfaces. Create a data Class Object and obtain its attributes:

var data = DataClass("NAME")println(data)println(data.name)
Print the property result:

02-07 09:50:05.995 3256-3256/? I/System.out: DataClass(name=NAME)02-07 09:50:05.995 3256-3256/? I/System.out: NAME
Kotlin defines a constant standard for the creation of data classes, which must be used to implement some common functions. When creating each data class, the compiler automatically exports the following Members from all attributes declared in the main constructor:
Equals ()/hashCode () pairs; toString () format is "DataClass (name = NAME)"; componentN () functions correspond to all attributes in declared order; Copy () function

The toString () method is the same as the data output above, and the attribute has been obtained. Let's print the equals and hasCode methods:

Log.e("=====", data.hashCode().toString())Log.e("=====", data.equals(data.copy(name = "Change")).toString())
Here we will introduce the copy attribute separately. copy Copies a certain attribute literally. However, kotlin allows users to modify attributes, or copy in an incomplete sense, A different object with different attributes is generated. Its internal method can be described as follows:

fun copy(name: String = this.name) =DataClass  (name)    
Now we copy the data object and change its name:

println(data.copy(name = "Change"))println(data)
Output result:

02-07 10:01:04.454 4444-4444/? I/System.out: DataClass(name=Change)02-07 10:01:04.454 4444-4444/? I/System.out: DataClass(name=NAME)
Deconstruct statement
Deconstruct Declaration: As the name implies, every parameter of the constructor is decomposed, and the object is created. The data created above is var data =.... Now we use the deconstruct function to create

Var (name) = DataClass ("A") // The name here can directly use Log. e ("=", name) 02-07 10:08:17. 444 5393-5393 /? E/======:
A sealed class is used to indicate a restricted class inheritance structure. When a value is of a finite set type, there is no other type. In a sense, they are extensions of enumeration classes: the value set of Enumeration type is also limited, but each enumeration constant only has one instance, A subclass of the seal class can contain multiple instances.
To declare a sealed class, you must add the sealed modifier before the class name. Although the sealed class can also have subclasses, all subclasses must be declared in the same file as the sealed class itself. (Before Kotlin 1.1, this rule is stricter: subclass must be nested inside the seal class Declaration ).

Create a seal class and its subclass:

sealed class Parentdata class ChildFirst(var name: String) : Parent()data class ChildSecond(var name: String):Parent()data class ChildThird(var name: String):Parent()
A seal class is self-abstract. It cannot be directly instantiated and can have abstract members. Non-private constructor is not allowed for the sealed class (its constructor is private by default ). Note that classes (indirect successors) that extend the sealing class subclass can be placed in any location, without the need to be in the same file. The key advantage of using the seal class is that when using the when expression, if the statement can be verified to overwrite all the situations, you do not need to add an else clause for the statement. Of course, this is only useful when you use when as an expression (using results) rather than as a statement.
fun getName(parent: Parent) : String? = when (parent){is ChildFirst -> parent.nameis ChildSecond -> parent.nameis ChildThird -> parent.name}
Internal class

In kotlin, a class can be nested inside a class. However, different from java, two classes are mutually independent in a sense, and internal Nested classes cannot use external data:

data class DataClass(var name: String) {        class Data {        fun print() {            Log.e("===========", "DataClass.Data")        }    }}DataClass.Data().print()//02-07 10:23:40.106 6569-6569/? E/===========: DataClass.Data
At this time, the nested class is not a nested class in a tired interior, because the internal class in kotlin needs a proprietary modifier: inner. Now we modify the nested class above:

var age: Int = 20inner class Data {     fun print() {         Log.e("===========",age.toString())     }}
At this time, the call method is different from the previous one. You must use an external class object to call:

Data. data (). print () 02-07 10:26:33. 767 6909-6909/com. example. administrator. kotlinpractise E // =============: 20 // output external class data
Anonymous internal class

When using object expressions to create an anonymous internal class instance, we will use Rxjava a lot, and we will create an anonymous object for the observer:

Observable.just(1).subscribe(object : Observer
 
  {    override fun onSubscribe(d: Disposable) {        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.    }    override fun onNext(t: Int) {        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.    }    override fun onComplete() {        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.    }    override fun onError(e: Throwable) {        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.    }})
 
Use object: T to create an anonymous internal class of T. Next we will create a ClickListener that is commonly used to set the click event:

air_view.setOnClickListener(object : View.OnClickListener{    override fun onClick(v: View?) {        println("Click")    }}
In kotlin, if the object is an instance of a functional Java interface (that is, a Java interface with a single abstract method), you can use a lambda expression with an interface type prefix to create it:

air_view.setOnClickListener{  println("Click")}
The creation and use of these three classes are briefly introduced here. As long as you know the form and meaning of their use, you can use them flexibly as needed.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.