Quick Answer

Mixing nullable and non-nullable types

Understanding the Issue

Kotlin's type system strictly separates nullable (Type?) and non-nullable (Type) types. This error occurs when passing a nullable value where non-null is expected.

The Problem

This code demonstrates the issue:

Kotlin Error
// Problem: Nullable where non-null expected
fun printLength(s: String) { ... }
val maybeString: String? = getString()
printLength(maybeString) // Error

The Solution

Here's the corrected code:

Kotlin Fixed
// Solution 1: Provide non-null value
printLength(maybeString ?: "default")

// Solution 2: Smart cast after check
if (maybeString != null) {
    printLength(maybeString) // Smart cast to String
}

// Solution 3: Change parameter type
fun printLength(s: String?) { ... }

Key Takeaways

Handle null cases explicitly when converting between nullable and non-null types.