kotlin-style.md
docs/kotlin-style.md
1# Kotlin Style & Formatting23## Formatting Rules45- **Indentation:** 4 spaces (no tabs).6- **Line length:** 120 characters maximum.7- **Code style:** Official Kotlin Coding Conventions / IntelliJ IDEA default Kotlin style.8- **Encoding:** UTF-8.9- **Blank lines:** Blank lines separate logical blocks. Always put a blank line before and after a `return` statement, a `when` expression, a loop (`for`, `while`), or a multiline chained call sequence — unless it is the first or last line in its enclosing block.1011## Automated Enforcement1213Do not rely on manual formatting review:14- Enforce formatting using **Spotless** (with ktlint) or **ktlint**:15 - Fix formatting:16 ```bash17 ./gradlew spotlessApply18 ```19 - Verify formatting in CI and pre-commit/pre-push quality gates:20 ```bash21 ./gradlew spotlessCheck22 ```2324## Variables & Immutability (`val` vs. `var`)2526- **Prefer `val` over `var` everywhere:**27 - Function parameters in Kotlin are implicitly `val` (immutable by definition).28 - Use `val` for all local variables, properties, and references by default.29 - Use `var` only when local mutable state is strictly necessary and cannot be cleanly expressed with immutability.30- **Type inference vs. explicit types:**31 - Use type inference (`val task = ...`) for local variables in **controllers** and **tests**, and where the type is obvious from the right-hand side expression.32 - Declare **explicit return types** on all `public` and `protected` functions in **services**, **repositories**, and **mappers** to ensure clear API contracts:33 ```kotlin34 fun searchTasks(pageable: Pageable): Page<Task>35 ```3637## Null Safety & Idiomatic Checks3839- Leverage Kotlin's type system (`String` vs. `String?`) — avoid nullable types unless nullability is a legitimate domain state.40- **Never use `!!` (not-null assertion):** Handle missing values gracefully or fail with a domain exception:41 ```kotlin42 val task = taskRepository.findByIdOrNull(id)43 ?: throw AppException(AppErrorMessage.TASK_NOT_FOUND)44 ```45- Use standard library null/blank checks:46 - `isNullOrEmpty()` and `isNullOrBlank()` on strings and collections.47 - `checkNotNull(...)` or `requireNotNull(...)` when enforcing internal invariants.4849## Data Classes & Constructors5051- **Parameter count:** Maximum 3 parameters on functions or constructors. If more related parameters are needed, group them into a Kotlin `data class`.52- **Data classes for models and DTOs:** Use `data class` with `val` properties for immutable models, DTOs, and value objects.53- **No builders needed:** Kotlin supports default argument values and named arguments. Do not use builder patterns or `@Builder`:54 ```kotlin55 val task = Task(56 id = dto.id,57 title = dto.title,58 status = TaskStatus.OPEN59 )60 ```61- Declare dependencies in the primary constructor in the class header:62 ```kotlin63 @Service64 @Transactional65 class TaskServiceImpl(66 private val taskRepository: TaskRepository,67 private val userClient: UserClient68 ) : TaskService { ... }69 ```7071## Language Idioms & Control Flow7273- **Expression bodies:** Use single-expression syntax (`fun calculate() = ...`) when a function consists of a single concise expression.74- **`when` expressions:** Prefer `when` expressions over chained `if` / `else if` / `else` or Java-style switches:75 ```kotlin76 val status = when (input) {77 "ACTIVE" -> Status.ACTIVE78 "INACTIVE" -> Status.INACTIVE79 else -> throw AppException(AppErrorMessage.INVALID_STATUS)80 }81 ```82- **Control flow:** Prefer early returns with guard clauses (`?: return ...`, `?: throw ...`) over deeply nested branches.83- **Collections:**84 - Prefer read-only collection interfaces (`List`, `Set`, `Map`) over mutable collections (`MutableList`).85 - Use idiomatic functional operations (`map`, `filter`, `associate`, `flatMap`, `firstOrNull`) rather than imperative loops.86- **Named conditions:** Wrap compound boolean conditions in a descriptive named `val` rather than inlining complex expressions.8788## Constants & No Magic Values8990- Replace magic numbers and strings with named constants.91- Define constants as `const val` within a `companion object` or as top-level private `const val` in the relevant file:92 ```kotlin93 companion object {94 private const val MAX_RETRY_ATTEMPTS = 395 }96 ```9798## Exceptions99100- Kotlin does not have checked exceptions. Do not use `@Throws` except for specific Java interop requirements.101- Throw unchecked domain exceptions (`throw AppException(AppErrorMessage.<X>)`).102103## Comments & Documentation104105- Omit comments on obvious or self-explanatory code.106- Reserve comments for cron expressions, non-trivial regex patterns, `TODO` markers, or `// given` / `// when` / `// then` test structure separators.107- Skip KDoc on obvious classes and methods.108109## Annotations & Overrides110111- The `override` keyword is compiler-enforced; always mark overridden interface or superclass methods with `override`.112- Ensure annotation targets are explicit when needed (e.g. `@field:Valid` on data class properties when Bean Validation requires field targeting).113114## Imports115116- No wildcard imports (`import foo.bar.*` is forbidden).117