0
0
Kotlinprogramming~10 mins

Why generics provide type safety in Kotlin - Test Your Understanding

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

Complete the code to declare a generic class that holds a value of any type.

Kotlin
class Box<[1]>(val value: T)
Drag options to blanks, or click blank then click option'
AType
BAny
CT
DValue
Attempts:
3 left
💡 Hint
Common Mistakes
Using a concrete type like Any instead of a generic parameter.
2fill in blank
medium

Complete the function signature to make it generic over type T.

Kotlin
fun <[1]> printValue(value: T) { println(value) }
Drag options to blanks, or click blank then click option'
AT
BValue
CAny
DType
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to declare the generic type parameter.
3fill in blank
hard

Fix the error by specifying the correct generic type in the list declaration.

Kotlin
val numbers: List<[1]> = listOf(1, 2, 3)
Drag options to blanks, or click blank then click option'
ANumber
BString
CAny
DInt
Attempts:
3 left
💡 Hint
Common Mistakes
Using String or Any which do not match the list elements.
4fill in blank
hard

Fill both blanks to create a generic function that returns the first element of a list.

Kotlin
fun <[1]> firstElement(list: List<[2]>): [1]? = list.firstOrNull()
Drag options to blanks, or click blank then click option'
AT
BInt
DString
Attempts:
3 left
💡 Hint
Common Mistakes
Using different types for the list and return value.
5fill in blank
hard

Fill all three blanks to create a generic class with a method that returns the stored value.

Kotlin
class Container<[1]>(private val item: [2]) {
    fun getItem(): [3] = item
}
Drag options to blanks, or click blank then click option'
AT
DAny
Attempts:
3 left
💡 Hint
Common Mistakes
Using different types for the property and return type.