0
0
Kotlinprogramming~10 mins

Generic function declaration 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 declare a generic function that returns the input value.

Kotlin
fun <T> identity(value: [1]): T {
    return value
}
Drag options to blanks, or click blank then click option'
AT
BAny
CInt
DString
Attempts:
3 left
💡 Hint
Common Mistakes
Using a concrete type like Int or String instead of the generic type T.
Using Any instead of the generic type T.
2fill in blank
medium

Complete the code to declare a generic function that swaps two values in a Pair.

Kotlin
fun <T> swap(pair: Pair<T, T>): Pair<T, T> {
    return Pair(pair.second, [1])
}
Drag options to blanks, or click blank then click option'
Apair
Bpair.first
Cpair.second
Dpair.swap
Attempts:
3 left
💡 Hint
Common Mistakes
Using pair.second twice instead of pair.first for the second element.
Trying to call a non-existent swap method on pair.
3fill in blank
hard

Fix the error in the generic function declaration that returns the first element of a list.

Kotlin
fun <T> firstElement(list: List<[1]>): T? {
    return list.firstOrNull()
}
Drag options to blanks, or click blank then click option'
AAny
BList
CT
DInt
Attempts:
3 left
💡 Hint
Common Mistakes
Using a concrete type like Int instead of the generic type T.
Using List without a type parameter.
4fill in blank
hard

Fill both blanks to declare a generic function that returns the size of a collection.

Kotlin
fun <[1]> collectionSize(collection: Collection<[2]>): Int {
    return collection.size
}
Drag options to blanks, or click blank then click option'
AT
BInt
DE
Attempts:
3 left
💡 Hint
Common Mistakes
Using different generic type names in declaration and parameter.
Using a concrete type like Int instead of a generic type.
5fill in blank
hard

Fill all three blanks to declare a generic function that returns a map from keys to values filtered by a predicate.

Kotlin
fun <[1], [2]> filterMap(
    map: Map<[1], [2]>,
    predicate: ([3], [2]) -> Boolean
): Map<[1], [2]> {
    return map.filter { (key, value) -> predicate(key, value) }
}
Drag options to blanks, or click blank then click option'
AK
BV
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up the order of generic types.
Using inconsistent generic type names.