Kotlin

Lesson 03

Sealed result states

Represent closed workflow outcomes with sealed types instead of status strings.

Good Code

src/main/kotlin/reviews/PublishResult.kt
sealed interface PublishResult {
    data object Published : PublishResult
    data class Rejected(val reason: String) : PublishResult
}

fun publish(review: Review): PublishResult {
    // The return type names every branch the caller must render.
    if (review.title.isBlank()) return PublishResult.Rejected("title_blank")
    return PublishResult.Published
}

Bad Code

PublishResult.kt
fun publish(review: Review): String {
    // String status hides the allowed workflow states from callers.
    if (review.title.isBlank()) return "bad"
    return "ok"
}

Review Notes

What to review

Good Code

The good version keeps Published and Rejected in the type system, so a when expression can cover every branch.

Bad Code

The bad version returns ad hoc strings. A typo or new status can reach the caller without a compiler signal.

Takeaways

  • A sealed result lets reviewers see every branch the caller must render or log.