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)
In Java, this would look something like:
public class JavaUser {
public JavaUser(String name, Int age) {
...
}
//getters
//setters
//equals()/hashCode()
//toString()
}
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
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:
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?
Thanks!
The coding style conventions give quite explicit guidance on this:
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).
The book Kotlin in Action says about source code layout (chapter 2.2.3, page 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).
So to answer your questions: it depends :)
来源:https://stackoverflow.com/questions/49281727/kotlin-data-class-packaging