0
0
Kotlinprogramming~5 mins

Generic function declaration in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a generic function in Kotlin?
A generic function is a function that can work with any data type. It uses a placeholder type, usually written as <T>, so you can use the same function for different types without rewriting it.
Click to reveal answer
beginner
How do you declare a generic function in Kotlin?
You declare a generic function by adding a type parameter in angle brackets before the function name, like this: fun <T> functionName(param: T) { ... }
Click to reveal answer
beginner
Why use generic functions instead of regular functions?
Generic functions let you write one function that works with many types, so you avoid repeating code and make your code more flexible and reusable.
Click to reveal answer
beginner
Example: What does this Kotlin function do?
fun <T> printItem(item: T) { println(item) }
This function prints any item you give it. The <T> means it can accept any type, like a number, text, or even a list.
Click to reveal answer
intermediate
Can a generic function have more than one type parameter? How?
Yes, you can declare multiple type parameters separated by commas, like fun example(a: T, b: U) { ... } to work with two different types.
Click to reveal answer
How do you start declaring a generic function in Kotlin?
ABy using the keyword generic
BBy adding () after the function name
CBy adding <T> before the function name
DBy writing fun generic()
What does the <T> in a generic function represent?
AA placeholder for any type
BA specific type like Int
CA function name
DA variable
Can a generic function accept different types each time it is called?
ANo, it only accepts one type
BOnly if the types are strings
COnly if the types are numbers
DYes, it can accept any type
Which of these is a correct generic function declaration?
Afun <T> show(item: T) { println(item) }
Bfun show<T>(item: T) { println(item) }
Cfun show(item: T) { println(item) }
Dfun <T> show(item) { println(item) }
How do you declare a generic function with two type parameters?
Afun <T U> example(a: T, b: U) { }
Bfun <T, U> example(a: T, b: U) { }
Cfun <T; U> example(a: T, b: U) { }
Dfun example<T, U>(a: T, b: U) { }
Explain how to declare and use a generic function in Kotlin with an example.
Think about how <T> works and how you can pass different types to the function.
You got /4 concepts.
    Why are generic functions useful? Describe a real-life situation where they help.
    Imagine writing one tool that works for many jobs instead of many tools for each job.
    You got /4 concepts.