Kotlin introduces the wonderful concept of Data Classes. These classes will derive the equals()/hashCode(), toString(), getters()/setters(), and a copy() function based on the properties declared in the constructor:

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

在Java中,这看起来像:

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

我的问题是关于用Kotlin打包这些数据类文件的问题.来自Java的我会将JavaUser存储在它自己的类文件中,位于:org.package.foo.JavaUser

由于数据类的简单性,我们在Kotlin中是否以相同的方式存储数据类文件?(即, for each 数据类org.package.foo.KotlinUser个和单独的文件).另外,在一个类文件中存储多个数据类是否不受欢迎?

org.package.foo.DataClasses包含:

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

I looked around in the idioms/coding style sections of the Kotlin Documentation and could not find anything about this (maybe I skimmed past it though). What is the best practice?

谢谢

推荐答案

The coding style conventions give quite explicit guidance on this:

鼓励在同一个Kotlin源文件中放置多个声明(类、顶级函数或属性),只要这些声明在语义上彼此密切相关,并且文件大小保持合理(不超过几百行).

Kotlin相关问答推荐

使用Jackson反序列化HTML列表时出现MismatchedInputResponse

在Kotlin中可以连接两个范围吗?

捕捉异常是Kotlin协程中的反模式吗?

Kotlin 中命名构造函数的惯用方式

ActivityResultContracts TakePicture 结果总是返回 false

mutableStateOf 在 Jetpack Compose 中不记住 API 的情况下保持重组后的值

如何在 Android Jetpack Compose 中的画布上绘制一侧加厚的描边?

Kotlin 编译器在构造函数中报告未使用的表达式,以便构建器采用 vararg lambda

kotlin 如何决定 lambda 中的参数名称?

如何在 Android 的 Fragment 中使用 setUserVisibleHint

如何为你的 Flutter 元素添加 Kotlin 支持?

零安全的好处

Intellij 显示 build.gradle.kts 中的每一行都是红色的

如何在Spring Boot应用程序上启用承载身份验证?

Tornadofx - 如何在每个实例上将参数传递给 Fragment

编译错误:-Xcoroutines has no effect: coroutines are enabled anyway in 1.3 and beyond

如何在Android Studio 4.1中默认启用Kotlin Android扩展

项目不会使用 Kotlin 1.1.3 构建

Kotlin 错误:public function exposes its 'public/*package*/' return type argument

RxJava - 每秒发出一个 observable