ListWithMultipleItemTypes.kt — Incorrect usage of items() lambda and contentType
- Dominant language
- Kotlin
- Stars
- 1.1k
- Forks
- 419
- Avg merge
- 3d 18h
- Merged PRs (30d)
- 28
Description
The code snippet in [ListWithMultipleItemTypes.kt](https://github.com/android/snippets/blob/a7117c0da26b85a9e005d700a7ae9dec859bb8bd/compose/snippets/src/main/java/com/example/compose/snippets/lists/ListWithMultipleItemTypes.kt#L28-L56) (used in the [Build a list with multiple item types](https://developer.android.com/develop/ui/compose/quick-guides/content/build-list-multiple-item-types) Quick Guide) contains multiple logical errors.
Current Code
```
@Composable
fun ListWithMultipleItems(messages: List) {
LazyColumn {
items(
messages.size,
contentType = { it }
) {
for (message in messages)
when (message) {
is MediaStore.Audio -> AudioMessage(message)
is Text -> TextMessage(message)
}
}
}
}
```
Issues
contentType = { it } returns the index (Int), not the content type. The it parameter inside the contentType lambda is the item index. This means every item gets a different content type (0, 1, 2, …), which completely defeats the purpose of contentType — Compose cannot reuse compositions across items of the same type. It should be something like { messages[it]::class }.
The items content lambda iterates the entire list for every single item. The lambda parameter it is the index of the current item, but instead of using messages[it] to render only the current item, the code uses for (message in messages) which iterates over all messages for each row. For a list of N items, this produces N × N composables instead of N.
This is confusing for developers trying to learn from the snippet.
Contributor guide
Research direction
Start with compose/snippets/src/main/java/com/example/compose/snippets/lists/ListWithMultipleItemTypes.kt at the referenced lines, then compare it with the Build a list with multiple item types Quick Guide. Verify the items lambda renders only the current message and that contentType reflects the message type; done means the snippet produces one row per message and can reuse compositions for matching types.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- kotlin
- Domain
- documentation
- Issue type
- Bug
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Quiet
- Clarity
- Clearly specified
- Newbie friendliness
- 82/100