Kotlin
Quiz model
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=...).
Exercise 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).
Show example 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)
}
Test yourself
-
Which is defined in the first lesson of the quiz application?
- runQuiz function
- Question data class and question list
- score function
- runMenu function
Show answer
Question data class and question list — The first lesson defines the Question data class and the list.
-
Complete the Question data class definition
data class ____(val text: String, val answer: String)
Show answer
data class Question(val text: String, val answer: String)
-
Match the Question parts
- data class Question
- Data class
- val text: String
- Question text
- val answer: String
- Correct answer
- MutableList<Question>
- Question list
Next lesson: Adding questions