0
0
Android Kotlinmobile~10 mins

Item keys for performance in Android Kotlin - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to assign a unique key to each item in a LazyColumn for better performance.

Android Kotlin
LazyColumn {
  items(items = itemList, key = [1]) { item ->
    Text(text = item.name)
  }
}
Drag options to blanks, or click blank then click option'
Aitem.id
Bitem.name
CitemList.size
Ditem.hashCode()
Attempts:
3 left
💡 Hint
Common Mistakes
Using itemList.size as key causes all items to have the same key.
Using item.name might not be unique if names repeat.
2fill in blank
medium

Complete the code to provide a stable key for each item in a RecyclerView adapter.

Android Kotlin
override fun getItemId(position: Int): Long {
  return [1]
}
Drag options to blanks, or click blank then click option'
ASystem.currentTimeMillis()
Bposition.toLong()
Citems.hashCode().toLong()
Ditems[position].id.toLong()
Attempts:
3 left
💡 Hint
Common Mistakes
Using position as ID can cause issues when items move.
Using current time causes keys to change every call.
3fill in blank
hard

Fix the error in the code to correctly set stable IDs in a RecyclerView adapter.

Android Kotlin
init {
  setHasStableIds([1])
}
Drag options to blanks, or click blank then click option'
Atrue
Bfalse
Cnull
Ditems.isNotEmpty()
Attempts:
3 left
💡 Hint
Common Mistakes
Passing false disables stable IDs, losing performance benefits.
Passing null causes a compile error.
4fill in blank
hard

Fill both blanks to create a LazyRow with items that have unique keys.

Android Kotlin
LazyRow {
  items(items = [1], key = [2]) { item ->
    Text(text = item.title)
  }
}
Drag options to blanks, or click blank then click option'
AmyItemList
Bitem.id
Citem.title
Ditems
Attempts:
3 left
💡 Hint
Common Mistakes
Using items instead of the actual list variable.
Using item.title as key may not be unique.
5fill in blank
hard

Fill all three blanks to create a RecyclerView adapter that uses stable IDs.

Android Kotlin
class MyAdapter(private val data: List<MyData>) : RecyclerView.Adapter<MyViewHolder>() {

  override fun getItemCount() = [1]

  override fun getItemId(position: Int): Long = [2]

  init {
    setHasStableIds([3])
  }

  // other adapter methods...
}
Drag options to blanks, or click blank then click option'
Adata.size
Bdata[position].uniqueId.toLong()
Ctrue
Dposition
Attempts:
3 left
💡 Hint
Common Mistakes
Returning position as ID instead of a unique stable ID.
Not enabling stable IDs with setHasStableIds(true).
Returning wrong item count.