Data classes in Kotlin

前端 未结 3 1321
谎友^
谎友^ 2021-02-20 18:21

What is the difference between:

Definition 1

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

Definition 2

class Person (va         


        
3条回答
  •  花落未央
    2021-02-20 18:57

    Briefly speaking:

    • Definition 1: this is a data class which primary constructor takes two parameters name and age
    • Definition 2: this is just a class which primary constructor takes two parameters name and age
    • Definition 3: this is a class which constructor has no arguments and assigns default values "" and 1 to the properties name and age respectively

    Detailed answered

    What is important to understand here is the concept of data class.

    Data Class

    It is very common to create classes whose main purpose is to hold data. If you want your class to be convenient holder for your data you need to override the universal object methods:

    • toString() - string representation
    • equals() - object equality
    • hashCode() - hash containers

    Note: equals() is used for structural equality and it is often implemented with hashCode().

    Usually, the implementation of these methods is straightforward, and your IDE can help you to generate them automatically.

    However, in Kotlin, you don't have to general all of these boilerplate code. If you add the modifier data to your class, the necessary methods are automatically added for you. The equals() and hashCode() methods take into account all the properties declared in the primary constructor. toString() will have the following format ClassName(parm1=value1, param2=value2, ...).

    In addition, when you mark a class as a data class, the method copy() is also automatically generated which allows you to make copies of an existing instance. This feature is very handy when you are using your instances as keys for a HashMap or if you are dealing with multithreaded code.

    Going back to your question:

    • Definition 1: you do not need to implement the universal object methods and you have also the copy() method ready to use
    • Definition 2: you will have to implement the universal object methods and the copy() method if you need them
    • Definition 3: you will have to implement the universal object methods and the copy() method if you need them, and there is no point in implementing the copy() method since your primary constructor has no parameters

    Even though the properties of a data class are not required to be val, i.e., you can use var as your are doing in your code, it is strongly recommended that you use read-only properties, so that you make the instances immutable.

    Finally, componentN() functions corresponding to the properties in their order of declaration are also generated by the compiler when you mark a class as a data class.

提交回复
热议问题