0
0
Kotlinprogramming~10 mins

Closures and variable capture 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 create a lambda that adds 5 to its input.

Kotlin
val addFive = { x: Int -> x [1] 5 }
Drag options to blanks, or click blank then click option'
A-
B+
C*
D/
Attempts:
3 left
💡 Hint
Common Mistakes
Using '-' instead of '+' causes subtraction.
Using '*' or '/' changes the operation to multiplication or division.
2fill in blank
medium

Complete the code to capture the variable 'factor' inside the lambda.

Kotlin
fun makeMultiplier(factor: Int): (Int) -> Int = { x -> x [1] factor }
Drag options to blanks, or click blank then click option'
A*
B+
C-
D/
Attempts:
3 left
💡 Hint
Common Mistakes
Using '+' adds instead of multiplies.
Using '-' or '/' changes the operation incorrectly.
3fill in blank
hard

Fix the error in the lambda to correctly capture the variable 'count'.

Kotlin
var count = 0
val increment = { count [1] 1 }
Drag options to blanks, or click blank then click option'
A=
B-=
C+=
D*=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '=' alone does not increment the value.
Using '-=' or '*=' changes the value incorrectly.
4fill in blank
hard

Fill both blanks to create a lambda that filters a list by length greater than 3.

Kotlin
val words = listOf("cat", "house", "dog", "elephant")
val filtered = words.filter { word -> word.length [1] [2] }
Drag options to blanks, or click blank then click option'
A>
B3
C<
D4
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' filters words shorter than 3.
Using 4 instead of 3 changes the filter condition.
5fill in blank
hard

Fill all three blanks to create a map of words to their uppercase versions for words longer than 4.

Kotlin
val words = listOf("apple", "bat", "carrot", "dog")
val result = words.filter { [1] -> [1].length [2] 4 }
    .associateWith { [3].uppercase() }
Drag options to blanks, or click blank then click option'
Aword
B>
Cit
Dlength
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'it' in filter parameter causes error.
Using '<' filters wrong words.
Using 'length' as variable name is incorrect.