Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Data Class packaging [closed]

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!

like image 712
Mike Henke Avatar asked Mar 14 '18 15:03

Mike Henke


People also ask

Is data class open Kotlin?

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.

How do you make a sealed class in Kotlin?

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.

What defines a sealed class in Kotlin?

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.

Can you extend a sealed class Kotlin?

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.


1 Answers

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

like image 72
yole Avatar answered Sep 22 '22 02:09

yole