Quick Answer

Attempting to assign null to non-nullable type

Understanding the Issue

Kotlin's type system distinguishes between nullable (Type?) and non-nullable (Type) types. This error occurs when trying to assign null to a variable declared as non-nullable.

The Problem

This code demonstrates the issue:

Kotlin Error
// Problem: Null assignment
val name: String = null // Error

The Solution

Here's the corrected code:

Kotlin Fixed
// Solution 1: Use nullable type
val name: String? = null

// Solution 2: Provide default value
val name: String = null ?: "Unknown"

// Solution 3: Initialize properly
val name: String = getName()

Key Takeaways

Always declare variables as nullable (Type?) if they might hold null values.