# 03 — Kotlin features through a Java lens

> **Assessment review:** The document-type update described below has a reproduced lost-update defect. Retaining a version is safe only when that version belongs to the state being changed. See [F2](../review.md#f2-document-type-partial-updates-can-overwrite-another-request-s-change).

Read the Kotlin as a set of explicit choices about state, absence, and construction. Shorter syntax is useful when it makes those choices clearer.

## Compare the idioms

| Java starting point | Kotlin in this backend | Consequence |
|---|---|---|
| Constructor plus final fields | Primary constructor with `private val` | Dependencies are explicit without Lombok |
| Record or immutable POJO | `data class` with `val` properties | Generated structural equality, destructuring, and `copy` |
| Nullable reference plus checks | `UUID?`, safe call `?.`, Elvis `?:` | Missing values appear in the type and control flow |
| Rebuild a record manually | `current.copy(name = value)` | Unspecified constructor properties are retained |
| Utility function for an enum | `private fun Role.canWrite()` | Static extension dispatch; no new enum member |
| Static helpers/constants | `object`, companion object, top-level declarations | Different JVM representations; inspect Java-facing APIs |
| Streams for transformations | `map`, `mapNotNull`, `associate`, `setOfNotNull` | Express transformations without an explicit stream pipeline |

A `val` prevents assigning a new reference; it does not freeze the referenced object. `DocumentUpload.content` is a `ByteArray`, so it can still be mutated. A data-class `copy()` is shallow. Kotlin read-only collection interfaces also do not guarantee that no other reference can mutate the collection. See the official [data classes documentation](https://kotlinlang.org/docs/data-classes.html).

## Absence has several meanings

`Document.id` is nullable because a new model has not been persisted. `teamId == null` means an owner-only document. `ocrContent == null` means content is absent, not necessarily that processing failed. An update's nullable property can mean “leave unchanged,” which differs from “clear it.” The document update model uses explicit clear flags to represent those operations.

Java interop can reintroduce uncertainty through platform types. `Optional<Document>` remains in persistence contracts; the service uses `orElseThrow` with a project-specific exception. Kotlin's compiler cannot prove all Java return values are non-null. See [Java interoperability](https://kotlinlang.org/docs/java-interop.html#null-safety-and-platform-types).

## Follow an immutable update

`DocumentTypeServiceImpl` checks uniqueness, loads the current snapshot, and creates a copy retaining the stored ID and version. Copying without the version loses concurrency information, but substituting a fresh version onto stale fields also breaks it. In this implementation the controller merges before the write transaction, so this is a counterexample to study and fix rather than a safe update template. The model is a snapshot, not a live JPA object whose changes are automatically tracked.

## Practice

Write equivalent Java and Kotlin versions of a small immutable classification model with nullable description. Implement rename in both. Add a mutable list to a separate scratch model and demonstrate that changing the list in a copy also changes the original's list. Then remove the mutable collection from your domain-facing API.

Rewrite `update.title?.let(::validateTitle)` as an explicit conditional. Explain that `let` executes only when the title exists and does not supply business validation by itself.

## Verification gate

Explain `val` versus deep immutability, `copy` versus persistence, and nullable values versus Java `Optional`. Show why a title update must preserve the optimistic version. Avoid introducing `!!` to hide an unresolved missing-value case.

## Read the implementation

- [DocumentUpload.kt](../reference/source/paperless-backend/src/main/kotlin/at/fhtw/swen3/paperless/document/model/DocumentUpload.kt)
- [DocumentUpdate.kt](../reference/source/paperless-backend/src/main/kotlin/at/fhtw/swen3/paperless/document/model/DocumentUpdate.kt)
- [DocumentType.kt](../reference/source/paperless-backend/src/main/kotlin/at/fhtw/swen3/paperless/documenttype/model/DocumentType.kt)
- [DocumentTypeServiceImpl.kt](../reference/source/paperless-backend/src/main/kotlin/at/fhtw/swen3/paperless/documenttype/service/DocumentTypeServiceImpl.kt)

## Complete source walkthrough

Read these pinned files alongside the explanation above. These are the inspected implementation, not the capstone solution.

### DocumentUpload.kt

[Browse source](../reference/source/paperless-backend/src/main/kotlin/at/fhtw/swen3/paperless/document/model/DocumentUpload.kt)

```kotlin
package at.fhtw.swen3.paperless.document.model

import java.util.UUID

data class DocumentUpload(
    val title: String,
    val originalFilename: String,
    val contentType: String,
    val content: ByteArray,
    val documentTypeId: UUID?,
    val teamId: UUID?
)
```

### DocumentUpdate.kt

[Browse source](../reference/source/paperless-backend/src/main/kotlin/at/fhtw/swen3/paperless/document/model/DocumentUpdate.kt)

```kotlin
package at.fhtw.swen3.paperless.document.model

import java.util.UUID

data class DocumentUpdate(
    val teamId: UUID?,
    val clearTeam: Boolean,
    val title: String?,
    val documentTypeId: UUID?,
    val clearDocumentType: Boolean = false
)
```

### DocumentType.kt

[Browse source](../reference/source/paperless-backend/src/main/kotlin/at/fhtw/swen3/paperless/documenttype/model/DocumentType.kt)

```kotlin
package at.fhtw.swen3.paperless.documenttype.model

import java.util.UUID

data class DocumentType(
    val id: UUID?,
    val name: String,
    val description: String?,
    val version: Long = 0
)
```

### DocumentTypeServiceImpl.kt

[Browse source](../reference/source/paperless-backend/src/main/kotlin/at/fhtw/swen3/paperless/documenttype/service/DocumentTypeServiceImpl.kt)

```kotlin
package at.fhtw.swen3.paperless.documenttype.service

import at.fhtw.swen3.paperless.documenttype.model.DocumentType
import at.fhtw.swen3.paperless.documenttype.persistence.DocumentTypePersistence
import at.fhtw.swen3.paperless.exception.DocumentTypeNameAlreadyExistsException
import at.fhtw.swen3.paperless.exception.DocumentTypeNotFoundException
import java.util.UUID
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

@Service
@Transactional
class DocumentTypeServiceImpl(
    private val repository: DocumentTypePersistence
) : DocumentTypeService {
    private val log = LoggerFactory.getLogger(javaClass)

    @Transactional(readOnly = true)
    override fun searchDocumentTypes(): List<DocumentType> =
        repository.findAll()

    override fun createDocumentType(documentType: DocumentType): DocumentType {
        if (repository.findByName(documentType.name) != null) {
            throw DocumentTypeNameAlreadyExistsException()
        }

        val saved = repository.save(documentType)
        log.info("[DOCUMENT_TYPE] - ACTION: createDocumentType: documentTypeId: {}", saved.id)

        return saved
    }

    @Transactional(readOnly = true)
    override fun getDocumentTypeById(id: UUID): DocumentType =
        findDocumentType(id)

    override fun updateDocumentType(id: UUID, documentType: DocumentType): DocumentType {
        val current = findDocumentType(id)
        val duplicate = repository.findByName(documentType.name)
        if (duplicate != null && duplicate.id != current.id) {
            throw DocumentTypeNameAlreadyExistsException()
        }

        val updated = documentType.copy(id = current.id, version = current.version)
        val saved = repository.save(updated)
        log.info("[DOCUMENT_TYPE] - ACTION: updateDocumentType: documentTypeId: {}", id)

        return saved
    }

    override fun deleteDocumentType(id: UUID) {
        repository.delete(findDocumentType(id))
        log.info("[DOCUMENT_TYPE] - ACTION: deleteDocumentType: documentTypeId: {}", id)
    }

    private fun findDocumentType(id: UUID) =
        repository.findById(id).orElseThrow { DocumentTypeNotFoundException() }
}
```
