Kotlin Data Class packaging

Mike Henke :

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!

yole :

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=441731&siteId=1