Summary - Arrays
- Kotlin course
- Beginner
- Lesson 58/116
- 5 min
Combine arrayOf, size and map to write a class list.
Summary - Arrays
In this summary you'll combine arrayOf, size and map to build a class list app. In previous lessons you learned:
- creating arrays with
arrayOfandintArrayOf - accessing elements with
arr[i] size,indices,lastIndex- iterating with
for map,filter,forEach
We'll do two mini tasks: add 10 points to grades (map) and filter passing grades (filter).
Practice Add 10 points to grades
Write a fun main(). Create a grades array with val grades = intArrayOf(50, 70, 90). Add 10 to each grade with val bonus = grades.map { it + 10 }. Print the result with println(bonus).
Starter code
fun main() {
// Add 10 points to grades
}Sample solution
fun main() {
val grades = intArrayOf(50, 70, 90)
val bonus = grades.map { it + 10 }
println(bonus)
}Expected output
[60, 80, 100]
Practice Filter passing grades
Write a fun main(). Create a grades array with val grades = intArrayOf(50, 30, 70, 20). Filter passing grades (50 and above) with val passing = grades.filter { it >= 50 }. Print the result with println(passing).
Starter code
fun main() {
// Filter passing grades
}Sample solution
fun main() {
val grades = intArrayOf(50, 30, 70, 20)
val passing = grades.filter { it >= 50 }
println(passing)
}Expected output
[50, 70]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which method transforms each element of an array?
- map Correct answer
- forEach
- filter
- size
Explanation: map transforms each element.
2 Complete the map call
val bonus = grades.____ { it + 10 }
val bonus = grades.map { it + 10 }
Explanation: grades.map { it + 10 } adds 10 to each grade.