Kotlin Null Safety Explained for Android Developers

Kotlin makes absence explicit in the type system. A String cannot contain null, while String? forces every caller to handle the missing-value case. On Android this removes a large class of crashes from Intent extras, database rows, network payloads and view state.

Practical guidance

  • Use nullable types only when absence is a valid domain state.
  • Prefer safe calls and the Elvis operator for small fallback decisions.
  • Convert platform and network values at repository boundaries instead of spreading null through the UI.
  • Use requireNotNull when missing data is a programmer or contract error, not as routine control flow.

Working example

data class UserUi(val name: String, val avatar: String?)

fun UserDto.toUi(): UserUi = UserUi(
    name = name?.trim().takeUnless { it.isNullOrEmpty() } ?: "Guest",
    avatar = avatarUrl
)

val length = user.avatar?.length ?: 0

Common mistakes

  • The !! operator postpones a null check until runtime and usually recreates a NullPointerException.
  • A nullable collection and a collection of nullable values communicate different contracts.
  • Java platform types should be validated immediately.

Key takeaway

Model null as a business decision. Once data crosses into a ViewModel or UI model, expose the strongest non-null contract you can guarantee.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top