Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 104 ยท Jetpack Compose Fundamentals

Composable Functions

Learn the rules of @Composable functions: naming, parameters, the modifier parameter, slots and trailing lambdas, emitting versus returning, and previews.

A Compose UI is built from one kind of building block: the composable function. It is an ordinary Kotlin function with the @Composable annotation, and it does not return a view. Instead, calling it describes a piece of UI, and the Compose runtime records that description. Small composables combine into bigger ones until a whole screen is a function that calls other functions.

This lesson covers the rules that every composable follows, the naming and parameter conventions you will see in all Compose code, how slots let a composable accept other UI as a parameter, and how previews work. The real code needs the Android SDK and the Compose libraries, so the Compose snippets are read-only. The runnable TryIt blocks are plain Kotlin stand-ins: a tiny composition builder that records the calls a composable makes, so you can watch emitting and slots work. For the big picture, see Thinking in Compose and the short Jetpack Compose basics.

What @Composable really does

The annotation tells the Compose compiler plugin (shipped with Kotlin since 2.0) to transform the function. The transformed version receives a hidden extra parameter, the composer, which it uses to record what the function emits. You never see or pass it: the compiler adds it, and passes it along to every composable you call.

Kotlin
// read-only example: needs Android and Compose
@Composable
fun Greeting(name: String) {
    Text(text = "Hello, $name!")
}

This has real consequences, and they are the rules of the road:

  • A composable can only be called from another composable (or from a lambda that Compose runs as composable, such as the one passed to setContent). A regular function or a click handler cannot call Text(...).
  • A composable may run again at any time. When state it reads changes, Compose calls it again (a recomposition). It may also skip a call when the inputs have not changed.
  • Calls may happen in any order and may be cancelled. So the body should be a fast description of UI, not a place for slow work or one-time actions. Side effects have dedicated tools, covered in Side Effects.
  • Do not write to variables outside the function in the body. Treat parameters as read-only inputs.

Think of a composable as a function from data to UI description: same inputs, same description.

Emitting versus returning

Most composables emit UI. They return Unit, and the effect of calling them is that nodes are added to the composition. Text, Button, Column and your own Greeting all do that.

A few composables return a value and emit nothing. remember { ... } returns whatever the lambda computed. rememberScrollState() returns a scroll state object. MaterialTheme.colorScheme is read in a composable context and returns colors. These are still composable, because they use the composer (to store or look up data), but they put nothing on screen.

The naming convention follows from this, and it is part of the official Compose API guidelines:

  • A composable that emits UI and returns Unit is named like a noun, in PascalCase: Greeting, ProfileCard, SearchBar.
  • A composable that returns a value is named like a normal function, in camelCase: rememberScrollState, rememberCoroutineScope. Functions that create and remember state conventionally start with remember.

A composable should either emit UI or return a value, not both. If you need to give a caller something back from a UI piece, expose it through a parameter (a callback or a state object), not a return value.

Parameters: the conventional order

Compose code is easy to read across projects because most composables share a layout:

  1. Required parameters come first: the data to show.
  2. modifier: Modifier = Modifier is the first optional parameter. It lets the caller change size, padding, click behavior and so on. Every reusable composable that emits UI should have it, and should apply it to its outermost element (Modifiers is a full lesson).
  3. Other optional parameters with defaults follow.
  4. A content lambda goes last, so callers can use trailing-lambda syntax.
Kotlin
// read-only example: needs Android and Compose
@Composable
fun ProfileCard(
    name: String,
    subtitle: String,
    modifier: Modifier = Modifier,
    elevated: Boolean = false,
    actions: @Composable () -> Unit = {},
) {
    Card(modifier = modifier) {
        Column(Modifier.padding(16.dp)) {
            Text(name, style = MaterialTheme.typography.titleMedium)
            Text(subtitle)
            actions()
        }
    }
}

Default values replace the overloads you would have needed in Java. Call sites name arguments freely: ProfileCard("Ada", "Mathematician", elevated = true).

Slots and trailing lambdas

A slot is a parameter of type @Composable () -> Unit: a hole in your composable that the caller fills with its own UI. The actions parameter above is a slot, and so is the content of Column { ... }.

Slots are how Compose achieves flexibility without inheritance. A Card does not know whether it will hold text, an image or a form; it just draws its surface and calls the slot. Because the slot is the last parameter, you write it with trailing-lambda syntax (see Lambdas and Higher-order functions):

Kotlin
// read-only example: needs Android and Compose
ProfileCard(name = "Ada", subtitle = "Mathematician") {
    Button(onClick = { /* follow */ }) { Text("Follow") }
}

The content lambda is itself composable, so inside it you can call other composables, use if and for, and read values from the outer scope. That is why Compose UI code looks like a normal program: control flow is just Kotlin.

Slots can also take parameters, for example item: @Composable (Product) -> Unit, which lets a list composable hand each row's data back to the caller to render.

A mini composition builder (stand-in)

The real runtime is much more sophisticated, but the shape can be modeled in a few lines. In the stand-in below, Text, Column and your own functions have no return value: they call emit, which adds a node to the node that is currently open. A Column opens a node, runs its content lambda (the slot), and closes it. Run it and compare the tree with the calls in Screen.

Kotlin Emitting nodes into a composition (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Notice what the stand-in does not contain: no object is returned from Greeting, and there is no Greeting.update() method. The tree is produced as a side product of running the functions, and a new run with new inputs produces a new description. In the real runtime the previous composition is kept and compared so only differences are applied to the screen.

Slots, defaults and returned values together

The second stand-in combines the conventions from this lesson: a Card with a default parameter, a slot for actions, a slot for content, and a camelCase function that returns a value instead of emitting.

Kotlin Defaults, slots and a returning function (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first card gets an elevated style and an action button because the caller passed them. The second uses the defaults. rememberLabel produced a string used as an argument and left no node behind.

flowchart TD
    A["Screen"] --> B["Column"]
    B --> C["Greeting('Ada')"]
    B --> D["Greeting('Linus')"]
    C --> E["Text"]
    D --> F["Text"]

Composables calling composables form a tree; each call to an emitting function adds a node.

Previews

Because composables are functions of their inputs, you can look at one without launching the app. Android Studio renders any composable annotated with @Preview:

Kotlin
// read-only example: needs Android and Compose
@Preview(showBackground = true)
@Composable
private fun ProfileCardPreview() {
    MyAppTheme {
        ProfileCard(name = "Ada", subtitle = "Mathematician", elevated = true)
    }
}

A preview function normally takes no parameters (or uses @PreviewParameter to feed sample data), and is often private. Wrap it in your theme so it looks like the app. Variants such as @PreviewLightDark and @PreviewFontScale render the same composable in several configurations. Previews run only in Studio and are not included in the release app. They work best for composables that take plain data, which is one more reason to keep UI functions free of hidden dependencies. The next lessons use previews constantly, and Running, Debugging and Logcat shows the tooling.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where can a @Composable function be called from?

    The compiler passes a hidden composer through composable calls, so only composable code (or a lambda Compose runs as composable) can call them. A click handler is a plain lambda and cannot call Text directly.
  2. 2. Which name follows the Compose convention for a function that emits UI and returns Unit?

    Emitting composables are named like nouns in PascalCase. camelCase names, often starting with remember, are for composables that return a value.
  3. 3. What is the purpose of the modifier parameter, and where does it go in the parameter list?

    By convention required data parameters come first, then modifier: Modifier = Modifier as the first optional one. It should be applied to the outermost element of the composable.
  4. 4. What is a slot?

    A slot is a composable lambda parameter. The composable decides where to place the content and the caller decides what it is.
  5. 5. Why should a composable body avoid slow work and one-time actions?

    Recomposition calls the function again whenever state it reads changes, so the body must be a fast, repeatable description of UI. Side effects use dedicated APIs such as LaunchedEffect.

Summary

  • A composable is a Kotlin function with @Composable; calling it describes UI, and the Compose compiler adds a hidden composer parameter.
  • Composables can only be called from other composables, and they may run repeatedly, in any order, or be skipped.
  • Emitting composables are PascalCase nouns returning Unit; value-returning ones are camelCase, often remember....
  • Conventional parameter order: required data, modifier: Modifier = Modifier, other optional parameters, then the content lambda last.
  • Slots (@Composable () -> Unit parameters) let callers supply UI; control flow inside them is ordinary Kotlin.
  • @Preview functions let Android Studio render composables without running the app.
  • The Compose code here is read-only; the TryIt blocks are stand-ins that model emitting and slots.

Next: Row, Column, Box and Arrangements