Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a generic class with two type parameters.
Kotlin
class Pair<[1], B>(val first: [1], val second: B)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase letters for type parameters.
Using non-letter characters.
✗ Incorrect
The first type parameter is commonly named T, so we use T for the first generic type.
2fill in blank
mediumComplete the function signature to use two generic type parameters.
Kotlin
fun <[1], [2]> createPair(first: [1], second: [2]): Pair<[1], [2]> = Pair(first, second)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the same type parameter twice.
Not declaring generic parameters before the function name.
✗ Incorrect
We use T and U as the two generic type parameters consistently in the function signature.
3fill in blank
hardFix the error in the generic class declaration with two type parameters.
Kotlin
class Box<[1], [2]>(val content1: [1], val content2: [2])
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Separating type parameters with spaces or semicolons.
Using only one type parameter when two are needed.
✗ Incorrect
Type parameters must be separated by commas inside angle brackets. So use T and U separated by a comma.
4fill in blank
hardFill both blanks to create a generic function that swaps two values of different types.
Kotlin
fun <[1], [2]> swap(pair: Pair<[1], [2]>): Pair<[2], [1]> = Pair(pair.second, pair.first)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the same type parameter for both elements.
Not swapping the type parameters in the return type.
✗ Incorrect
We use T and U as the two generic type parameters consistently to swap the pair elements.
5fill in blank
hardFill all three blanks to define a generic class with three type parameters and a method returning a Triple.
Kotlin
class TripleHolder<[1], [2], [3]>(val first: [1], val second: [2], val third: [3]) { fun toTriple(): Triple<[1], [2], [3]> = Triple(first, second, third) }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using fewer than three type parameters.
Not matching the type parameters in the method return type.
✗ Incorrect
We use A, B, and C as the three generic type parameters consistently in the class and method.