Skip to content

ListWithMultipleItemTypes.kt — Incorrect usage of items() lambda and contentType #863

@hijamoya

Description

@hijamoya

The code snippet in ListWithMultipleItemTypes.kt (used in the Build a list with multiple item types Quick Guide) contains multiple logical errors.

Current Code

@Composable
fun ListWithMultipleItems(messages: List<Any>) {
    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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions