AlgoGalaxy

AlgoGalaxy

University
CodeRush
Jobs
Tools
Insights
Explore
Personalize
JavaGoPHPRustGraphsTreesArraysDynamic ProgrammingGreedyHashingHeapLinked ListNumber TheoryStackStringsTrieUnion FindBacktrackingBinary SearchBit Manipulation

Kotlin | Null Safety

Kotlin makes nullability part of the type system. A non-null String cannot hold null, while String? requires an explicit safe access, fallback, check or deliberate failure policy before its value is used.

Nullable Types Are Explicit

String and String? are different types. Declare a nullable value only when absence is valid in the model; otherwise validate input at the boundary and keep the rest of the codebase non-null.

Safe Calls and Elvis

The safe-call operator returns null instead of dereferencing a null receiver. Combine it with Elvis to provide a default or return early, keeping absence handling close to the operation that may observe it.

Smart Casts

After a stable null check, Kotlin smart-casts a value to its non-null type. Avoid mutable shared references that can change between check and use; capture a local value when concurrency or callbacks matter.

Avoid the Non-Null Assertion

!! converts a nullable value into a runtime crash if it is null. It is appropriate only when an external invariant has already been proven and a failure should expose a violated contract immediately.

Platform Types Need Boundaries

Java APIs can expose platform types with uncertain nullability. Wrap them in Kotlin functions that validate or normalize the value once rather than spreading uncertainty through every caller.

Worked Examples

Example 1: Format an Optional Name

The safe call evaluates uppercase only when name is present. Elvis supplies a stable UI fallback without a nested if statement.

Code

fun displayName(name: String?): String =
    name?.trim()?.uppercase() ?: "GUEST"

fun main() {
    println(displayName(null))
    println(displayName("  nova "))
}

Expected Result

GUEST
NOVA

Example 2: Return Early for Missing Input

An early return turns the nullable argument into a non-null local path. The business operation below the guard no longer needs repeated null checks.

Code

fun createSlug(title: String?): String? {
    val value = title ?: return null
    return value.trim().lowercase().replace(" ", "-")
}

fun main() {
    println(createSlug("Kotlin Null Safety"))
    println(createSlug(null))
}

Expected Result

kotlin-null-safety
null

Example 3: Use let for a Present Value

let runs its lambda only when the safe-call receiver is non-null. The result remains nullable because no result exists when the input is absent.

Code

fun lengthLabel(value: String?): String? =
    value?.let { "length=" + it.length }

fun main() {
    println(lengthLabel("orbit"))
    println(lengthLabel(null))
}

Expected Result

length=5
null

Example 6: Make the input visible

Start by naming the value the next line depends on. This keeps the lesson input explicit before we apply a transformation or call an external boundary. We are applying that habit while revisiting Kotlin Null Safety.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Kotlin

fun review(value: String?): String =
    value?.trim()?.takeIf { it.isNotEmpty() }?.uppercase()
        ?: "needs a value"

fun main() {
    println(review("Kotlin Null Safety"))
}

Expected Result

KOTLIN NULL SAFETY

Try next: Replace the sample value with one from your own notes, predict the result, and then run it.

Example 7: Guard an empty boundary

A small guard makes the allowed and rejected path visible. We want a caller to receive an intentional result instead of discovering an unexplained failure later. We are applying that habit while revisiting Kotlin Null Safety.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Kotlin

fun review(value: String?): String =
    value?.trim()?.takeIf { it.isNotEmpty() }?.uppercase()
        ?: "needs a value"

fun main() {
    println(review("Kotlin Null Safety"))
}

Expected Result

KOTLIN NULL SAFETY

Try next: Try an empty value as well as the normal value and describe why the two outcomes differ.

Example 8: Keep the transformation pure

This step returns a value instead of mixing the rule with display or storage work. That separation gives us a small unit we can run, test, and reuse. We are applying that habit while revisiting Kotlin Null Safety.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Kotlin

fun review(value: String?): String =
    value?.trim()?.takeIf { it.isNotEmpty() }?.uppercase()
        ?: "needs a value"

fun main() {
    println(review("Kotlin Null Safety"))
}

Expected Result

KOTLIN NULL SAFETY

Try next: Call the same rule twice with different inputs and confirm that each result depends only on its input.

Example 9: Make a branch deliberate

Use a named branch where the business rule changes. A future reader should be able to point at the condition and state the result for both sides. We are applying that habit while revisiting Kotlin Null Safety.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Kotlin

fun review(value: String?): String =
    value?.trim()?.takeIf { it.isNotEmpty() }?.uppercase()
        ?: "needs a value"

fun main() {
    println(review("Kotlin Null Safety"))
}

Expected Result

KOTLIN NULL SAFETY

Try next: Change the boundary value by one and explain exactly which branch becomes active.

Example 10: Use a collection without hidden mutation

Collections become safer when we can see which value is read, which value is derived, and whether the original collection remains owned by the caller. We are applying that habit while revisiting Kotlin Null Safety.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Kotlin

fun review(value: String?): String =
    value?.trim()?.takeIf { it.isNotEmpty() }?.uppercase()
        ?: "needs a value"

fun main() {
    println(review("Kotlin Null Safety"))
}

Expected Result

KOTLIN NULL SAFETY

Try next: Add one more item and predict the derived result before executing the code.

Example 11: Return a named outcome

A named outcome is easier to test than an implied side effect. We can now distinguish a successful path from a rejected path without guessing from console noise. We are applying that habit while revisiting Kotlin Null Safety.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Kotlin

fun review(value: String?): String =
    value?.trim()?.takeIf { it.isNotEmpty() }?.uppercase()
        ?: "needs a value"

fun main() {
    println(review("Kotlin Null Safety"))
}

Expected Result

KOTLIN NULL SAFETY

Try next: Rename the outcome in your own words while preserving the same success and failure rule.

Example 12: Trace a small loop

Work through one value at a time. The point is not to memorize syntax; it is to see how the accumulator or output changes after each repeatable step. We are applying that habit while revisiting Kotlin Null Safety.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Kotlin

fun review(value: String?): String =
    value?.trim()?.takeIf { it.isNotEmpty() }?.uppercase()
        ?: "needs a value"

fun main() {
    println(review("Kotlin Null Safety"))
}

Expected Result

KOTLIN NULL SAFETY

Try next: Use a shorter collection first, then add one value and trace the extra iteration aloud.

Example 13: Keep display at the edge

The core rule prepares a value, while the outer line decides how to show it. That keeps the result usable by a UI, test, API, or command-line caller. We are applying that habit while revisiting Kotlin Null Safety.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Kotlin

fun review(value: String?): String =
    value?.trim()?.takeIf { it.isNotEmpty() }?.uppercase()
        ?: "needs a value"

fun main() {
    println(review("Kotlin Null Safety"))
}

Expected Result

KOTLIN NULL SAFETY

Try next: Change only the display text and verify that the underlying rule and result stay unchanged.

Example 14: Test the closest boundary

A useful example includes the nearest boundary, not only the happy path. We are making the behavior inspectable before a real caller relies on it. We are applying that habit while revisiting Kotlin Null Safety.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Kotlin

fun review(value: String?): String =
    value?.trim()?.takeIf { it.isNotEmpty() }?.uppercase()
        ?: "needs a value"

fun main() {
    println(review("Kotlin Null Safety"))
}

Expected Result

KOTLIN NULL SAFETY

Try next: Try the lowest supported value and then one value just outside the accepted range.

Example 15: Write a tiny regression check

A compact assertion turns the lesson into a repeatable promise. It helps us catch a changed rule before a larger program hides the source of the mistake. We are applying that habit while revisiting Kotlin Null Safety.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Kotlin

fun review(value: String?): String =
    value?.trim()?.takeIf { it.isNotEmpty() }?.uppercase()
        ?: "needs a value"

fun main() {
    println(review("Kotlin Null Safety"))
}

Expected Result

KOTLIN NULL SAFETY

Try next: Deliberately change the expected value once, observe the failed check, and then restore the correct contract.

Complexity Analysis

Operation Complexity Explanation
Safe call O(1) overhead The receiver is checked before the property or function is evaluated.
String normalization O(n) time Trimming and replacement inspect the string characters.
Boundary validation O(1) decision A null guard prevents deeper invalid execution.

Common Mistakes

  • Using !! as a routine replacement for explicit absence handling.
  • Making every value nullable instead of modelling absence at the correct boundary.
  • Calling a Java platform API repeatedly without normalizing its possible null result.
  • Using a mutable nullable property after a check when another path can change it.

Interview Checklist

  • State whether null means absent, unknown, not found or invalid.
  • Choose safe call, Elvis or early return based on the caller contract.
  • Keep validated values non-null for the rest of the operation.
  • Test null, blank, normal and Java-interoperability boundary values.

Additional Kotlin Practice

These extra runnable examples complete the practice set for this lesson. Read each result in order, then adjust one local value before moving to the next topic.

Additional Example 1: Model one immutable value

Run this compact Kotlin program, then change one input and predict the new result. Keep values explicit, validate untrusted input at a boundary, and return a value or named failure a caller can test.

Kotlin

data class Topic(val id: String, val title: String)

fun main() {
    val topic = Topic("k-1", "Kotlin")
    println(topic.title)
}

Expected Result

Kotlin

Try next: make the nearest invalid or empty case observable instead of relying on an unchecked assumption.

Additional Example 2: Validate an input at the boundary

Run this compact Kotlin program, then change one input and predict the new result. Keep values explicit, validate untrusted input at a boundary, and return a value or named failure a caller can test.

Kotlin

fun port(value: Int): Int {
    require(value in 1..65535) { "invalid port" }
    return value
}

fun main() = println(port(443))

Expected Result

443

Try next: make the nearest invalid or empty case observable instead of relying on an unchecked assumption.

logo of AlgoGalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

AlgoGalaxy University

University HomeTechnology LearningCoding ProblemsLearning ProgressCareer OpportunitiesTechnology InsightsUtilNexa ToolsAlgoGalaxy HomeContact Support

AlgoGalaxy CodeRush

CodeRush HomeProblem SetsProgress TrackerLearn TechnologyTechnology JobsEngineering InsightsDeveloper UtilitiesAlgoGalaxy HomePrivacy Policy
Privacy Policy

 • 

Terms of Service

Copyright © AlgoGalaxy 2026