DM
Technical reference

Kotlin Cheatsheet

Modern programming for Android and the JVM

Must Know

java

Values and Null Safety

Prefer immutable val and explicit nullable types.

val name: String = "Luis"
var nickname: String? = null
val length = nickname?.length ?: 0
java

Data Class

Data classes provide equality, copy, and destructuring.

data class User(val id: Long, val name: String)

val updated = user.copy(name = "Ana")

Important Patterns

java

Sealed Result

Sealed types make state handling exhaustive.

sealed interface Result<out T> {
  data class Success<T>(val value: T) : Result<T>
  data class Error(val cause: Throwable) : Result<Nothing>
}
java

Coroutines

Use structured concurrency and appropriate dispatchers.

viewModelScope.launch {
  val user = withContext(Dispatchers.IO) { repository.loadUser() }
  _state.value = user
}

Useful Recipes

java

Collection Pipeline

val names = users
  .filter { it.active }
  .sortedBy { it.name }
  .map { it.name }
java

Scope Functions

Choose scope functions for clarity, not brevity.

user.apply { name = "Luis" }
user?.let { render(it) }
with(config) { connect(host, port) }

Pitfalls & Production

java

Coroutine Errors

Know whether sibling failure should cancel the whole operation.

supervisorScope {
  val first = async { loadFirst() }
  val second = async { loadSecond() }
}

Avoid !!

Handle absence at boundaries instead of forcing non-null.

val user = repository.find(id) ?: return NotFound
// Avoid user!!