0
0
Kotlinprogramming~10 mins

Function references (::functionName) 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 function reference to the 'println' function.

Kotlin
val printer = [1]println
printer("Hello, Kotlin!")
Drag options to blanks, or click blank then click option'
A->
B.
C::
D=>
Attempts:
3 left
💡 Hint
Common Mistakes
Using '.' instead of '::' which calls the function instead of referencing it.
Using '->' or '=>' which are not valid for function references in Kotlin.
2fill in blank
medium

Complete the code to pass a function reference of 'isEven' to the 'filter' function.

Kotlin
fun isEven(n: Int) = n % 2 == 0
val numbers = listOf(1, 2, 3, 4)
val evens = numbers.filter([1]isEven)
println(evens)
Drag options to blanks, or click blank then click option'
A::
B.
C->
D=>
Attempts:
3 left
💡 Hint
Common Mistakes
Using '.' which tries to call the function instead of referencing it.
Using lambda syntax '->' or '=>' which is incorrect here.
3fill in blank
hard

Fix the error by completing the code to create a function reference to the 'toUpperCase' method of String.

Kotlin
val toUpper: (String) -> String = [1]String::toUpperCase
println(toUpper("kotlin"))
Drag options to blanks, or click blank then click option'
AString::
B::
CString.
D.
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'String::' before 'String::toUpperCase' which is redundant.
Using '.' which tries to call the method instead of referencing it.
4fill in blank
hard

Fill both blanks to create a map of words to their lengths using a function reference and a property reference.

Kotlin
val words = listOf("apple", "banana", "cherry")
val lengths = words.associateWith([1]) { it.[2] }
println(lengths)
Drag options to blanks, or click blank then click option'
AString::length
Blength
DString.length
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'String.length' which is invalid syntax.
Using 'length' without context or as a string.
5fill in blank
hard

Fill all three blanks to filter a list of strings by length using a function reference and a lambda.

Kotlin
val words = listOf("cat", "dog", "elephant", "fox")
val filtered = words.filter { word -> word.length [1] [2] }
val lengthCheck: (String) -> Boolean = [3] { it.length > 3 }
println(filtered)
println(filtered.filter(lengthCheck))
Drag options to blanks, or click blank then click option'
A>
B3
C::
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' which filters the wrong words.
Not using '::' when assigning the lambda to the function variable.