0
0
Kotlinprogramming~20 mins

Generic function declaration in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Generic Function Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a simple generic function
What is the output of this Kotlin code that uses a generic function to return the input value?
Kotlin
fun <T> identity(value: T): T {
    return value
}

fun main() {
    println(identity(42))
}
Anull
Bidentity(42)
C42
DCompilation error
Attempts:
2 left
💡 Hint
Think about what the function returns when given an integer.
🧠 Conceptual
intermediate
1:30remaining
Understanding generic function type parameters
In Kotlin, what does the in the function declaration fun echo(item: T): T mean?
AIt declares a generic type parameter T that can be any type.
BIt specifies that T is always an Int type.
CIt restricts the function to only accept String types.
DIt is a syntax error and should be removed.
Attempts:
2 left
💡 Hint
Generic type parameters allow flexibility in the function input and output types.
Predict Output
advanced
2:00remaining
Output of generic function with multiple types
What is the output of this Kotlin code that uses a generic function with two type parameters?
Kotlin
fun <A, B> pairToString(a: A, b: B): String {
    return "$a and $b"
}

fun main() {
    println(pairToString(10, "apples"))
}
A10 and apples
B10 and 10
Capples and 10
DCompilation error
Attempts:
2 left
💡 Hint
Look at how the function combines the two parameters into a string.
🔧 Debug
advanced
2:00remaining
Identify the error in this generic function declaration
What error does this Kotlin code produce? fun printTwice(value: T) { println(value) println(value) } fun main() { printTwice() }
Kotlin
fun <T> printTwice(value: T) {
    println(value)
    println(value)
}

fun main() {
    printTwice()
}
ACompilation error: Generic type T not specified
BCompilation error: No value passed for parameter 'value'
CPrints two blank lines
DRuntime error: NullPointerException
Attempts:
2 left
💡 Hint
Check the function call and its parameters.
🚀 Application
expert
2:30remaining
Result of generic function with nullable type and default value
What is the output of this Kotlin code that uses a generic function with a nullable type and a default value?
Kotlin
fun <T> defaultIfNull(value: T?, default: T): T {
    return value ?: default
}

fun main() {
    println(defaultIfNull(null, "Hello"))
    println(defaultIfNull("World", "Hello"))
}
ACompilation error
Bnull\nWorld
CHello\nHello
DHello\nWorld
Attempts:
2 left
💡 Hint
The Elvis operator ?: returns the left value if not null, otherwise the right value.