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

以下是我的数据类代码:

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

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

下面是数据类的结果:

[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]

这是否意味着在Kotlin中普通类和数据类是不同的?如果是,那是什么?

Updated:

谢谢@Mallow,你说得对.这很有效:

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))
}

推荐答案

for a data class.

编译器会自动从所有

equals()/hashCode()对,

toString()的形式为"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

Kotlin相关问答推荐

如果启用了Flyway迁移,则不能具有配置属性';datources.default.架构-生成

jOOQ Kotlin Coroutines - Select all and exists查询

如何定义一个函数来接受任何具有特定字段的数据类

在 Kotlin 中将 Array 转换为 IntArray 时丢失值

从 Kotlin 的父类获取函数注解

在Kotlin lambda的参数中如何指定函数类型?

为什么在jacksonObjectMapper上将DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES设置为false无效?

Kotlin 中的as Long和.toLong()有什么区别?

在 Compose 中使用 Text() 时如何获取文本的大小?

PRDownloader 即使在实现库后也无法工作.未知参考:Android Studio 中的 PRDownloader

Kotlin 插件错误:无法为类 org.jetbrains.kotlin.gradle.tasks.KotlinCompile 生成代理类

无法从 XML 访问 NavHostFragment

使用最新的 com.jakewharton.rxbinding3:rxbinding:3.0.0-alpha2 库时未找到 RxTextView 和其他小部件

如何在调试中修复 ClassNotFoundException: kotlinx.coroutines.debug.AgentPremain?

如何从定义它们的类外部调用扩展方法?

包括登录Elvis operator?

Android Studio 将 Java 转换为 Kotlin 错误无法推断此参数的类型

如何解决:将Java类转换为Kotlin后出现error: cannot find symbol class ...?

Kotlin中具有多个参数的绑定适配器

在kotlin中初始化类变量的正确位置是什么