Kotlin数据类包装 [英] Kotlin Data Class packaging

查看:325
本文介绍了Kotlin数据类包装的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Kotlin介绍了数据类的精彩概念。这些类将派生 equals()/ hashCode() toString() getters ()/ setters(),以及基于构造函数中声明的属性的 copy()函数:

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:

数据类KotlinUser(val name:String,val age:Int)

In Java,这看起来像:

In Java, this would look something like:

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

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

My question is about the packaging of these data class files in Kotlin. Coming from Java I would store JavaUser in its own Class file under: org.package.foo.JavaUser

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

Due to the simplicity of a Data Class, do we store Data Class files the same way in Kotlin? (I.e. org.package.foo.KotlinUser and seperate files for each Data Class). Also, is it frowned upon to store multiple Data Classes in one Class file?:

org.package.foo.DataClasses contains:

org.package.foo.DataClasses contains:

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

我环顾了成语/编码风格的部分Kotlin文档并没有找到任何关于此的信息(也许我已经略过了它)。什么是最佳做法?

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源文件中放置多个声明(类,顶级函数或属性),只要这些声明与这些声明密切相关彼此在语义上和文件大小保持合理(不超过几百行)。

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

这篇关于Kotlin数据类包装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆