Compose
- Kotlin course
- Expert
- Lesson 46/47
- 6 min
Write UI with Compose Multiplatform.
UI with Compose
The fourth lesson represents the Compose Multiplatform UI layer. A @Composable function draws data onto the screen.
In our model the noteView function takes a Note and returns its title as a string. Real Compose would feed this string to a Text component; we model it by printing to the console. The call noteView(b.build()) connects the builder output to the UI. This is the bridge between the data layer and the UI.
The noteView and builder bridge
The noteView function carries the builder output to the UI. The call noteView(b.build()) bridges data and UI.
Example model: fun noteView(note: Note): String = note.title. In main you write val b = NoteBuilder(); b.title = "Compose"; println(noteView(b.build())). This corresponds to a Text component in real Compose. The data flow is unidirectional: the builder produces, noteView draws.
Practice Add the noteView function
Define fun noteView(note: Note): String = note.title. In main, do val b = NoteBuilder(); b.title = "Compose" and write println(noteView(b.build())).
Starter code
object App {
fun run(): String = "Expert Notes"
}
data class Note(val id: Int, val title: String)
annotation class AutoBuilder
class NoteBuilder {
var id = 0
var title = ""
fun build(): Note = Note(id, title)
}
// add the noteView function (note: Note) -> String
fun main() {
// build a Note with NoteBuilder, show it with noteView, and print
}Sample solution
object App {
fun run(): String = "Expert Notes"
}
data class Note(val id: Int, val title: String)
annotation class AutoBuilder
class NoteBuilder {
var id = 0
var title = ""
fun build(): Note = Note(id, title)
}
fun noteView(note: Note): String = note.title
fun main() {
val b = NoteBuilder()
b.title = "Compose"
println(noteView(b.build()))
}Expected output
Compose
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the noteView declaration
@Composable fun NoteView(note: ____): String { return note.title }
@Composable fun NoteView(note: Note): String { return note.title }
Explanation: noteView(note: Note) takes a Note and returns the title.
2 Match the Compose parts
| Term | Meaning |
|---|---|
noteView |
UI function |
b.build() |
Data source |
note.title |
Shown text |
Text |
Real component |
3 Which paradigm does Compose MP use to build UI?
Compose builds UI with declarations.- Imperative
- XML layout
- Procedural
- Declarative Correct answer
Explanation: Compose builds UI with the declarative paradigm.