Lesson 4: The Kotlin You Need Before Writing Compose
The Kotlin You Need Before Writing Compose
Before we write our first real screen in the next lesson, let's make sure the Kotlin fundamentals are solid — Compose leans on a few specific patterns constantly.
If you haven't read the Kotlin primer yet, do that first
This course assumes the material in Kotlin Basics Part 1 and Part 2. If variables, functions, null safety, data classes, and lambdas aren't familiar yet, go read those two pages now — everything from here on assumes them.
The one Kotlin feature Compose relies on most: trailing lambdas
// A function that takes a lambda as its last parameter...
fun doSomething(action: () -> Unit) {
action()
}
// ...can be called like this:
doSomething {
println("Running!")
}This "curly braces instead of parentheses" pattern is exactly what Compose's UI code looks like — every layout you write (Column { }, Button(onClick = { }) { }) is built on this exact Kotlin feature.
Functions as parameters
fun onButtonClick(callback: () -> Unit) {
// do something, then...
callback()
}
onButtonClick {
println("Button was clicked")
}You'll write this pattern constantly: a composable takes an onClick: () -> Unit parameter, and you pass in exactly what should happen — this is how Compose handles every button, every tap, every user interaction.
The @Composable annotation, previewed
@Composable
fun Greeting(name: String) {
Text("Hello, $name!")
}You'll see @Composable above every UI function from the next lesson onward. For now, just know: it's an annotation that tells Kotlin "this function describes part of the UI," and it unlocks the ability to call other composable functions like Text inside it.
Next: Lesson 5 — writing your first Composable function.