Kotlin 数据 Class 打包

Kotlin Data Class packaging

Kotlin 引入了 Data Classes 的美妙概念。这些 classes 将根据构造函数中声明的属性派生 equals()/hashCode()toString()getters()/setters()copy() 函数:

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

在 Java 中,这看起来像:

public class JavaUser {
    public JavaUser(String name, Int age) {
       ...
    }
    //getters
    //setters
    //equals()/hashCode()
    //toString()
}

我的问题是关于这些数据 class 文件在 Kotlin 中的打包。来自 Java 我会将 JavaUser 存储在其自己的 Class 文件中: org.package.foo.JavaUser

由于数据 Class 的简单性,我们在 Kotlin 中以相同的方式存储数据 Class 文件吗? (即 org.package.foo.KotlinUser 和每个数据的单独文件 Class)。此外,将多个数据 Class 存储在一个 Class 文件中是否令人不悦?:

org.package.foo.DataClasses 包含:

data class Foo(val a: String, val b: String)
data class Bar(val a: Int, val b: Int)

我查看了 Kotlin 文档的 idioms/coding 样式部分,但找不到任何相关信息(也许我略过了)。最佳做法是什么?

谢谢!

Kotlin in Action这本书说了源代码布局(第 2.2.3 章,第 27 页):

In Kotlin, you can put multiple classes in the same file and choose any name for that file.

...

In most cases, however, it's still good practice to follow Java's directory layout and to organize files into directories according to the package structure. Sticking to that structure is especially important in projects where Kotlin is mixed with Java.

...

But you shouldn't hesitate to pull multiple classes into the same file, especially if the classes are small (and in Kotlin, they often are).

所以回答你的问题:视情况而定:)

编码风格约定 quite explicit guidance 对此:

Placing multiple declarations (classes, top-level functions or properties) in the same Kotlin source file is encouraged as long as these declarations are closely related to each other semantically and the file size remains reasonable (not exceeding a few hundred lines).