Quiz model
- Kotlin course
- Intermediate
- Lesson 42/116
- 6 min
Design the Question data class and list.
Quiz model
In this five-lesson project you will build a quiz application. Each lesson adds one piece, and the final lesson brings everything together.
You will use what you learned in previous groups: data class, MutableList and menu loops. In the first lesson you will define the Question data class and an empty question list. In main you will add one question and print it. Throughout the project you will build question adding, running, score calculation and menu integration functions on top of this model.
Question and MutableList
A data class is suitable for carrying data. The Question class carries the question text and the correct answer. MutableList lets questions be added dynamically.
Example: data class Question(val text: String, val answer: String). An empty list is started with val questions: MutableList<Question> = mutableListOf(). A question is added via questions.add(Question("Capital city?", "Ankara")). questions[0].text returns the first question text. The data class toString looks like Question(text=..., answer=...).
Practice Question and question list
Define data class Question(val text: String, val answer: String). Declare an empty list with val questions: MutableList<Question> = mutableListOf(). In main add a question with questions.add(Question("Capital city?", "Ankara")) and print the first question text with println(questions[0].text).
Starter code
// Define the Question data class
// an empty mutable list named questions
// add one question in main and print its textSample solution
data class Question(val text: String, val answer: String)
val questions: MutableList<Question> = mutableListOf()
fun main() {
questions.add(Question("Capital city?", "Ankara"))
println(questions[0].text)
}Expected output
Capital city?
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is defined in the first lesson of the quiz application?
- runQuiz function
- Question data class and question list Correct answer
- score function
- runMenu function
Explanation: The first lesson defines the Question data class and the list.
2 Complete the Question data class definition
data class ____(val text: String, val answer: String)
data class Question(val text: String, val answer: String)
Explanation: data class Question defines the question model.
3 Match the Question parts
| Term | Meaning |
|---|---|
data class Question |
Data class |
val text: String |
Question text |
val answer: String |
Correct answer |
MutableList<Question> |
Question list |