Kotlin for Android
Since 2019 Google has been "Kotlin-first": new Android APIs, documentation and samples are written in Kotlin, and the modern UI toolkit Jetpack Compose only exists in Kotlin. Everything you learned in this course — null safety, data classes, lambdas, sealed classes, coroutines — is used daily in Android apps.
Android apps can't run in this browser, so this chapter explains the concepts with code you'd write in Android Studio, plus small simulated previews of what the screens look like.
The pieces of an Android app
| Piece | What it does |
|---|---|
Activity |
an entry point with a window — typically one MainActivity |
| Composable functions | describe the UI (@Composable fun …) |
ViewModel |
holds screen state and survives screen rotation |
Gradle (build.gradle.kts) |
builds the app, manages dependencies |
AndroidManifest.xml |
declares the app's name, icon, permissions and activities |
Jetpack Compose basics
In Compose, the UI is a tree of composable functions. You don't create and modify view objects; you describe what the screen should look like for the current state, and Compose redraws whatever changes.
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MaterialTheme {
Greeting(name = "Android")
}
}
}
}
@Composable
fun Greeting(name: String) {
Column(modifier = Modifier.padding(16.dp)) {
Text("Hello, $name!", style = MaterialTheme.typography.headlineSmall)
Text("Built with Kotlin and Compose")
}
}Notice the Kotlin features at work: trailing lambdas (setContent { … }, Column { … }), named arguments (modifier = …), default arguments (most Text parameters are optional) and extension properties (16.dp).
Here's a simulated preview of that screen (an HTML mock — press ▶ to render it):
<div style="width:320px;margin:12px auto;border:1px solid #ccc;border-radius:18px;overflow:hidden;font-family:Roboto,system-ui,sans-serif;background:#fffbfe">
<div style="height:22px;background:#e7e0ec"></div>
<div style="padding:16px">
<div style="font-size:24px;color:#1c1b1f">Hello, Android!</div>
<div style="font-size:14px;color:#49454f;margin-top:4px">Built with Kotlin and Compose</div>
</div>
<div style="height:380px"></div>
</div>State and recomposition
Compose re-runs ("recomposes") a composable when the state it reads changes. remember { mutableStateOf(…) } stores state across recompositions:
@Composable
fun Counter() {
var count by remember { mutableStateOf(0) }
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text("You tapped $count times", fontSize = 20.sp)
Button(onClick = { count++ }) {
Text("Tap me")
}
}
}Tapping the button changes count; Compose notices and redraws the Text. The by keyword is a delegated property, just like by lazy. This interactive mock behaves the same way:
<div style="width:320px;margin:12px auto;border:1px solid #ccc;border-radius:18px;overflow:hidden;font-family:Roboto,system-ui,sans-serif;background:#fffbfe;text-align:center">
<div style="background:#7f52ff;color:#fff;padding:16px;font-size:20px;text-align:left">Counter</div>
<div style="padding:40px 16px">
<div id="label" style="font-size:20px;margin-bottom:16px">You tapped 0 times</div>
<button id="btn" style="background:#6750a4;color:#fff;border:0;border-radius:20px;padding:10px 24px;font-size:14px;cursor:pointer">Tap me</button>
</div>
</div>
<script>
let count = 0;
document.getElementById('btn').onclick = () => {
count++;
document.getElementById('label').textContent = `You tapped ${count} times`;
};
</script>ViewModel, StateFlow and coroutines
Real screens keep their state in a ViewModel. It exposes a StateFlow that the UI observes, and loads data in viewModelScope — coroutines that are cancelled automatically when the screen is closed:
sealed interface NotesUiState {
data object Loading : NotesUiState
data class Ready(val notes: List<String>) : NotesUiState
data class Error(val message: String) : NotesUiState
}
class NotesViewModel(private val repo: NotesRepository) : ViewModel() {
private val _state = MutableStateFlow<NotesUiState>(NotesUiState.Loading)
val state: StateFlow<NotesUiState> = _state
init {
viewModelScope.launch {
_state.value = try {
NotesUiState.Ready(repo.loadNotes()) // suspend fun
} catch (e: IOException) {
NotesUiState.Error("No connection")
}
}
}
}
@Composable
fun NotesScreen(vm: NotesViewModel) {
val state by vm.state.collectAsState()
when (val s = state) {
NotesUiState.Loading -> CircularProgressIndicator()
is NotesUiState.Ready -> LazyColumn {
items(s.notes) { note -> Text(note, Modifier.padding(12.dp)) }
}
is NotesUiState.Error -> Text(s.message, color = Color.Red)
}
}This is where the course's ideas come together: a sealed interface models the screen states, when handles every case exhaustively, the private mutable / public read-only pattern protects the state, and coroutines do the loading.
The plain-Kotlin core
The logic behind a screen is ordinary Kotlin that you can run and test without a phone. For example, the filtering behind a search box:
data class Note(val title: String, val pinned: Boolean)
fun visibleNotes(all: List<Note>, query: String): List<Note> =
all.filter { it.title.contains(query, ignoreCase = true) }
.sortedWith(compareByDescending<Note> { it.pinned }.thenBy { it.title })
fun main() {
val notes = listOf(
Note("Shopping list", false),
Note("Kotlin tips", true),
Note("Trip packing list", false),
Note("Gift ideas", true)
)
visibleNotes(notes, "").forEach { println((if (it.pinned) "* " else " ") + it.title) }
println("--- search 'list' ---")
visibleNotes(notes, "list").forEach { println(it.title) }
}* Gift ideas
* Kotlin tips
Shopping list
Trip packing list
--- search 'list' ---
Shopping list
Trip packing list
Tip: Keep business logic out of composables and activities. Pure functions like
visibleNotesare easy to unit-test and can even be shared with iOS via Kotlin Multiplatform (next chapter).
Getting started
- Install Android Studio and create a project from the Empty Activity template.
- Run it on the built-in emulator or a phone with USB debugging enabled.
- Follow Google's free Android Basics with Compose course to build real apps step by step.
Test yourself
What is Jetpack Compose?
- A build tool
- Android's modern declarative UI toolkit written in Kotlin
- A database
- A testing library
Why is viewModelScope.launch preferred over GlobalScope.launch in Android?
- It is faster
- Its coroutines are cancelled automatically when the ViewModel is cleared
- It runs on a new thread
- GlobalScope doesn't exist
What causes a composable to be redrawn (recomposed)?
- A timer every frame
- A change in the state it reads
- Calling invalidate() manually
- Rotating the device only