Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
148 views
in Technique[技术] by (71.8m points)

What is the difference between a normal class and a data class in Kotlin?

I tried to resolve task #6 (DataClass) at Kotlin Koans. When I used the normal class in code, the test case failed.

Here's my code of the data class:

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

fun task6(): List<Person> {
    return listOf(Person("Alice", 29), Person("Bob", 31))
}

Here's result of the data class:

[Person(name=Alice, age=29), Person(name=Bob, age=31)]

Here's my code of the normal class:

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

fun task6(): List<Person> {
    return listOf(Person("Alice", 29), Person("Bob", 31))
}

Here's result of the normal class:

[i_introduction._6_Data_Classes.Person@4f47d241, i_introduction._6_Data_Classes.Person@4c3e4790]

Does that mean there is difference between a normal class and a data class in Kotlin. If yes, what is that?

Updated:

Thank @Mallow, you are right. That works:

class Person(val name: String, val age: Int) {
    override fun toString(): String {
        return "Person(name=$name, age=$age)"
    }
}

fun task6(): List<Person> {
    return listOf(Person("Alice", 29), Person("Bob", 31))
}
question from:https://stackoverflow.com/questions/44193821/what-is-the-difference-between-a-normal-class-and-a-data-class-in-kotlin

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

for a data class.

The compiler automatically derives the following members from all properties declared in the primary constructor:

equals()/hashCode() pair,

toString() of the form "User(name=John, age=42)",

componentN() functions corresponding to the properties in their order of declaration,

copy() function (see below).

see https://kotlinlang.org/docs/reference/data-classes.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...