Kotlin
Adding questions
Learn to add questions with the addQuestion function.
Adding questions
In the second lesson we add the addQuestion function. It takes a question text and an answer, and adds a new Question to the list.
Example: fun addQuestion(text: String, answer: String) { questions.add(Question(text, answer)) }. This function is called as addQuestion("2+2?", "4"). The questions list is declared at file scope, so the function reaches it directly. To add multiple questions you call the function again. The data model and list come from the first lesson; this lesson only adds the function.
Adding multiple questions
Each call to addQuestion grows the list. Every call adds a new Question instance.
Example: addQuestion("Capital city?", "Ankara"); addQuestion("2+2?", "4"). After these two calls questions has two items. Calling println(questions) prints [Question(text=Capital city?, answer=Ankara), Question(text=2+2?, answer=4)]. Thanks to the data class's automatic toString, the list content is readable.
Exercise Add two questions with addQuestion
Build on the first lesson's solution: data class Question(val text: String, val answer: String) and val questions: MutableList<Question> = mutableListOf() are defined. Add a fun addQuestion(text: String, answer: String) function whose body does questions.add(Question(text, answer)). In main call addQuestion("Capital city?", "Ankara") and addQuestion("2+2?", "4"), then print the list with println(questions).
Show example solution
data class Question(val text: String, val answer: String)
val questions: MutableList<Question> = mutableListOf()
fun addQuestion(text: String, answer: String) {
questions.add(Question(text, answer))
}
fun main() {
addQuestion("Capital city?", "Ankara")
addQuestion("2+2?", "4")
println(questions)
}
Test yourself
-
Complete the addQuestion function
fun addQuestion(text: String, answer: String) {
questions.____(Question(text, answer))
}
Show answer
fun addQuestion(text: String, answer: String) {
questions.add(Question(text, answer))
}
-
Match the addQuestion parts
- fun addQuestion(text, answer)
- Function signature
- questions.add
- List append
- Question(text, answer)
- New question instance
- addQuestion("2+2?", "4")
- Call
-
How does the <code>addQuestion</code> function access the <code>questions</code> list?
- It takes it as a parameter
- Through a singleton
- Directly, because it is declared at file scope
- From a companion object
Show answer
Directly, because it is declared at file scope — questions is declared at file scope; the function reaches it directly.
Next lesson: Running the quiz