What is the difference between a normal class and a data class in kotlin

I tried to enable Kotlin Koan when setting number 6 (DataClass). When I used a regular class in the code, the test case is a failure.

Here is my data class code:

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

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

Here is the result of the data class:

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

Here is my normal class code:

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

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

Here is the result of the normal class:

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

This means the difference between the normal class and the data class in Kotlin. So what is this?

Update

Thanks @Mallow, you're right. This work:

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))
}
+6
source share
2 answers

for the data class.

The compiler automatically infers the following members from all properties declared in the main constructor:

equal to () / hashCode () pair,

toString() " ( = , = 42)",

componentN(), ,

copy() (. ).

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

+6

, (, ) , .

:

, , . . data.

, :

  • equals()/hashCode(),
  • toString() " ( = , = 42)",
  • componentN(), ,
  • copy() (. ). - , .

, data-classes

- , - toString(). toString() . general class 'toString() - .

+2

All Articles