Use Data Class
ID |
kotlin.use_data_class |
Severity |
info |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Kotlin |
Tags |
best-practice, code-style |
Description
Reports a regular class that behaves like a plain data carrier: its primary
constructor declares only val/var parameters, the body adds no functions,
init blocks, secondary constructors, or additional properties, and the class
has no supertypes. Declaring it as data class is shorter and gives
equals, hashCode, toString, copy and componentN for free.
Rationale
// Manual data carrier — boilerplate is unavoidable
class Point(val x: Int, val y: Int)
Without the data modifier the compiler will not generate value-equality
overrides, copy(), or destructuring components, which is almost always what
the author meant. Anyone using the type in collections, tests, or logs will
have to reinvent the missing operations.
Remediation
// Idiomatic Kotlin data carrier
data class Point(val x: Int, val y: Int)
Add the data modifier. If the class actually carries behaviour, give it a
member function and the rule will no longer fire.