@Composable
- Kotlin course
- Expert
- Lesson 32/47
- 5 min
Learn to write components with @Composable.
What is @Composable?
@Composable is the annotation that marks a function as a UI component. Compose only includes these functions in the UI tree.
A @Composable function returns Unit; it takes data as parameters and describes UI. Example: @Composable fun Greeting(name: String) { Text("Hi, $name") }. This function is called from inside another @Composable. Compose redraws the function when its data changes. The greeting model in this lesson shows the concept.
Principles of @Composable
A @Composable function may only be called from inside another @Composable. It returns Unit and takes data as parameters.
Composable functions must be pure: the same input produces the same UI. Side effects go into SideEffect or LaunchedEffect. This purity lets Compose skip unnecessary recomposition. When state changes, only the related composable redraws. This keeps UI performance high.
Practice Write greeting
Define fun greeting(name: String): String. It should return "Hi, $name!". In main, write println(greeting("Ayşe")).
Starter code
// add the greeting function
fun main() {
// print the greeting result
}Sample solution
fun greeting(name: String): String = "Hi, $name!"
fun main() {
println(greeting("Ayşe"))
}Expected output
Hi, Ayşe!
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the @Composable declaration
____ fun Greeting(name: String) { }
@Composable fun Greeting(name: String) { }
Explanation: The @Composable annotation makes the function a UI component.
2 Match the @Composable parts
| Term | Meaning |
|---|---|
@Composable |
UI function |
Unit |
Return type |
name: String |
Parameter |
Greeting |
Component name |
3 What does a @Composable function return?
A composable returns no value.- String
- Unit Correct answer
- Int
- Boolean
Explanation: A @Composable function returns Unit; it describes UI.