0
0
Kotlinprogramming~10 mins

Iterating collections with forEach in Kotlin - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to print each number in the list using forEach.

Kotlin
val numbers = listOf(1, 2, 3, 4, 5)
numbers.forEach { [1] -> println([1]) }
Drag options to blanks, or click blank then click option'
Anumber
Bitem
Cnum
Dvalue
Attempts:
3 left
💡 Hint
Common Mistakes
Using a keyword or invalid variable name as the lambda parameter.
Leaving the lambda parameter blank.
2fill in blank
medium

Complete the code to print each fruit in uppercase using forEach.

Kotlin
val fruits = listOf("apple", "banana", "cherry")
fruits.forEach { [1] -> println([1].uppercase()) }
Drag options to blanks, or click blank then click option'
Aitem
Bfruits
Cfruit
Df
Attempts:
3 left
💡 Hint
Common Mistakes
Using the plural 'fruits' as the lambda parameter.
Using a variable name not matching the context.
3fill in blank
hard

Fix the error in the forEach lambda parameter to correctly print each name.

Kotlin
val names = listOf("Anna", "Bob", "Cara")
names.forEach { [1] -> println([1]) }
Drag options to blanks, or click blank then click option'
Alist
Bname
Cn
Dnames
Attempts:
3 left
💡 Hint
Common Mistakes
Using the collection name 'names' as the lambda parameter.
Using unrelated variable names.
4fill in blank
hard

Fill both blanks to create a map of word lengths for words longer than 3 characters.

Kotlin
val words = listOf("cat", "house", "tree", "a", "elephant")
val lengths = words.filter { it.length [1] 3 }.associateWith { [2].length }
Drag options to blanks, or click blank then click option'
A>
Bword
C<
Dit
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' in the filter condition.
Using 'word' instead of 'it' inside associateWith.
5fill in blank
hard

Fill all three blanks to create a map of uppercase keys and their lengths for words starting with 'a'.

Kotlin
val words = listOf("apple", "banana", "apricot", "cherry", "avocado")
val result = words.filter { [1].startsWith("a") }.associateBy([2].uppercase()) { [3].length }
Drag options to blanks, or click blank then click option'
Ait
Bword
Dw
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names inconsistently.
Using 'it' in associateBy lambdas when a named parameter is expected.