0
0
Kotlinprogramming~10 mins

Generic constraints with where clause 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 with a constraint using the where clause.

Kotlin
fun <T> checkValue(value: T) where T : [1] {
    println(value)
}
Drag options to blanks, or click blank then click option'
ANumber
BString
CAny
DList
Attempts:
3 left
💡 Hint
Common Mistakes
Using a class like String which is not a numeric type.
Not using the where clause properly.
Using Any which does not constrain the type.
2fill in blank
medium

Complete the code to declare a generic function with two constraints using the where clause.

Kotlin
fun <T> process(item: T) where T : Comparable<T>, T : [1] {
    println(item)
}
Drag options to blanks, or click blank then click option'
ACharSequence
BNumber
CList
DAny
Attempts:
3 left
💡 Hint
Common Mistakes
Using a non-numeric type like CharSequence.
Not including both constraints properly.
Using Any which does not constrain the type.
3fill in blank
hard

Fix the error in the generic function declaration by completing the where clause correctly.

Kotlin
fun <T> compareValues(a: T, b: T) where T : [1], T : Comparable<T> {
    println(if (a > b) a else b)
}
Drag options to blanks, or click blank then click option'
AAny
BString
CNumber
DList
Attempts:
3 left
💡 Hint
Common Mistakes
Using Any which does not guarantee comparability.
Using String which is not numeric.
Omitting the where clause.
4fill in blank
hard

Fill both blanks to declare a generic function with constraints that T must be a Number and implement Comparable.

Kotlin
fun <T> maxValue(a: T, b: T) where T : [1], T : [2] {
    println(if (a > b) a else b)
}
Drag options to blanks, or click blank then click option'
ANumber
BCharSequence
CComparable<T>
DList
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping the order of constraints incorrectly.
Using non-numeric or non-comparable types.
Omitting one of the constraints.
5fill in blank
hard

Fill all three blanks to declare a generic function with constraints that T must be a Number, implement Comparable, and also implement CharSequence.

Kotlin
fun <T> complexCheck(item: T) where T : [1], T : [2], T : [3] {
    println(item)
}
Drag options to blanks, or click blank then click option'
ANumber
BComparable<T>
CCharSequence
DList
Attempts:
3 left
💡 Hint
Common Mistakes
Using incompatible types together.
Omitting one or more constraints.
Mixing up the order of constraints.