java - Kotlin 数据类打包

标签 java kotlin coding-style convention

Kotlin 引入了数据类的奇妙概念。这些类将派生 equals()/hashCode()toString()getters()/setters() >copy() 函数基于构造函数中声明的属性:

数据类 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 存储在它自己的 Class 文件中: org.package.foo.JavaUser

由于数据类的简单性,我们在 Kotlin 中存储数据类文件的方式是否相同? (即 org.package.foo.KotlinUser 和每个数据类的单独文件)。另外,在一个 Class 文件中存储多个 Data 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 style 部分,但没有找到任何相关信息(也许我略过了它)。最佳做法是什么?

谢谢!

最佳答案

编码风格约定给出 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).

关于java - Kotlin 数据类打包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49281727/

相关文章:

android - 在 Android 中使用 Hilt 后无法创建 View 模型实例

vb.net - 局部变量 : Pascal or Camel Casing?

java - 如何从其 String 值中查找 Java 枚举?

java - 将 Gradle 项目导入 Eclipse 时出错

java - 2D Java 游戏。在平铺图像上方移动 Sprite

kotlin - Kotlin:表达 “`字符串?` contains `字符串的最佳方法”

java - spring 4.3.7 和 weblogic 12.2.1 Rest 集成有错误

android - 用Facebook登录,第二次登录时Firebase正在改变UID,Kotlin Android Studio

CSS 大小声明

java - "Equality test with boolean literal"- 测试 boolean 值和使用 == 之间的区别