Data Class Functions

ID

kotlin.data_class_functions

Severity

info

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Kotlin

Tags

data_class, separation_of_concerns

Description

Reports data class declarations that define member functions beyond the compiler-generated ones (equals, hashCode, toString, copy, componentN). A data class is intended to be a pure data carrier — mixing additional logic inside it dilutes its contract.

Rationale

data class types are designed around value-equality semantics and the auto-generated overrides. Once business logic is added as member functions the type stops being a transparent record: changes to its behaviour become coupled to changes in its shape, and equality starts to mean both "same data" and "same behaviour", which is rarely intended. Moving logic out into top-level helpers or extension functions keeps the data class focused on the data and avoids surprises in copy semantics and serialization.

// Bad — business logic on a data class
data class Point(val x: Int, val y: Int) {
    fun distance() = Math.sqrt((x * x + y * y).toDouble())
}

// Good — extension function keeps the data class clean
data class Point(val x: Int, val y: Int)
fun Point.distance() = Math.sqrt((x * x + y * y).toDouble())

Remediation

Move non-generated functions out of the data class body. Use top-level functions, extension functions on the data class, or a separate behaviour-bearing class that owns a reference to the data.