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!
Kotlin Data Class Requirements The parameters of the primary constructor must be marked as either val (read-only) or var (read-write). The class cannot be open, abstract, inner or sealed. The class may extend other classes or implement interfaces.
Implementing Kotlin Sealed Classes To specify a sealed class, you need to add the modifier sealed . A sealed class cannot be instantiated. Hence, are implicitly abstract.
Sealed classes are used for representing restricted class hierarchies, when a value can have one of the types from a limited set, but cannot have any other type.
All direct subclasses of a sealed class are known at compile time. No other subclasses may appear outside a module within which the sealed class is defined. For example, third-party clients can't extend your sealed class in their code.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With