androidengineers.Book a session

Null Safety and the Type System

Practice: Null-Safety Implementation

exercise35 minEasy

Normalize optional enrollment data

Build a small boundary function for a course enrollment. Input consists of a required learner name and optional study minutes, both arriving as nullable strings. Blank names must fail; missing minutes should use 25; explicitly invalid minutes must fail rather than use the default.

data class Enrollment(val learner: String, val minutes: Int)

fun enroll(name: String?, minutes: String?): Enrollment? {
    val learner = name?.trim()?.takeIf { it.isNotEmpty() } ?: return null
    val budget = if (minutes == null) 25 else minutes.trim().toIntOrNull()
    if (budget == null || budget <= 0) return null
    return Enrollment(learner, budget)
}

The conditional preserves the difference between missing and malformed input. Using minutes?.toIntOrNull() ?: 25 would silently default both cases. That behavior might be suitable elsewhere, but violates this exercise's contract.

Acceptance checks

Verify a normal enrollment, surrounding whitespace, a missing name, a blank name, absent minutes, "abc", "0", and "-1". Implement a display label for success and a friendly message for failure.

Extension: introduce a sealed result identifying which field failed. Explain why nullable fields in an input DTO do not require nullable fields throughout the domain model.

Reference: Null safety

YOUR LEARNING JOURNEY

0 of 110 available lessons completed

Progress saved in this browser. No account needed.
Practice: Null-Safety Implementation | Kotlin Core Programming | Android Engineers