Real World Example

Rendering a Mixed Home Feed

The home screen of apps like Instagram, YouTube or Flipkart mixes different item types (banners, product rows, ads). RecyclerView adapters and Compose LazyColumns check each item's type and smart cast it to draw the right layout.

Example

data class Banner(val imageUrl: String, val title: String)
data class ProductRow(val heading: String, val products: List<String>)
data class Ad(val sponsor: String)

fun renderFeed(items: List<Any>) {
    for (item in items) {
        val line = when (item) {
            is Banner -> "[BANNER] ${item.title}"
            is ProductRow -> "[ROW] ${item.heading}: ${item.products.joinToString(" | ")}"
            is Ad -> "[AD] Sponsored by ${item.sponsor}"
            is String -> "[TEXT] $item"
            else -> "[SKIPPED] unknown item"
        }
        println(line)
    }
}

fun main() {
    renderFeed(listOf(
        Banner("https://cdn/sale.png", "Big Billion Days"),
        ProductRow("Deals on Mobiles", listOf("Pixel 9", "OnePlus 13")),
        Ad("Zepto"),
        "Recommended for you",
        42,
    ))
}

Output

[BANNER] Big Billion Days
[ROW] Deals on Mobiles: Pixel 9 | OnePlus 13
[AD] Sponsored by Zepto
[TEXT] Recommended for you
[SKIPPED] unknown item

Tip: In real code, prefer a sealed interface FeedItem over Any: the same when with smart casts becomes exhaustive and there is no unknown-type branch.

Android: Adapter View Types

class FeedAdapter(private val items: List<FeedItem>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    override fun getItemViewType(position: Int) = when (items[position]) {
        is FeedItem.Banner -> R.layout.item_banner
        is FeedItem.Products -> R.layout.item_product_row
        is FeedItem.Ad -> R.layout.item_ad
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (val item = items[position]) {
            is FeedItem.Banner -> (holder as BannerHolder).bind(item)     // item smart cast to Banner
            is FeedItem.Products -> (holder as ProductRowHolder).bind(item)
            is FeedItem.Ad -> (holder as AdHolder).bind(item)
        }
    }
    // onCreateViewHolder, getItemCount ...
}