Kotlin Quiz Engines: Category-Safe Question Loading

Quiz apps feel easy until category filters, localization, and randomization collide. Then users report seeing wrong questions in the wrong section. Here’s a safer architecture.

Step 1: Model category and question contracts explicitly

data class Question(
    val id: String,
    val categoryId: String,
    val prompt: String,
    val options: List<String>,
    val answerIndex: Int
)

Step 2: Filter first, randomize second

fun pickQuestions(all: List<Question>, categoryId: String, limit: Int): List<Question> {
    return all
        .asSequence()
        .filter { it.categoryId == categoryId }
        .shuffled()
        .take(limit)
        .toList()
}

Step 3: Detect malformed question sets before runtime

fun validate(questions: List<Question>) {
    require(questions.none { it.options.isEmpty() })
    require(questions.all { it.answerIndex in it.options.indices })
}

Pitfalls to avoid

  • Applying randomization before category filter.
  • Question IDs duplicated across packs.
  • No startup validation for malformed options.

Validation checklist

  • Category pages only show category-owned questions.
  • Malformed question packs fail during validation, not during quizzes.
  • Randomization stays stable under seeded test mode.

Get New Tutorials by Email

No spam. Just clear, practical breakdowns you can apply right away.

Enjoy this tutorial?

Get new practical tech tutorials in your inbox.