0
0
Kotlinprogramming~5 mins

Multiple type parameters in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does it mean to have multiple type parameters in Kotlin?
It means a generic class or function can work with more than one type, each represented by a separate type parameter like <T, U>.
Click to reveal answer
beginner
How do you declare a Kotlin function with two type parameters?
You write the function with <T, U> before the function name, for example: <br>fun <T, U> pairToString(pair: Pair<T, U>): String { return "${pair.first} and ${pair.second}" }
Click to reveal answer
beginner
What is the benefit of using multiple type parameters?
It lets you write flexible code that can handle different types together, like pairs or maps, without losing type safety.
Click to reveal answer
intermediate
Example: What does this Kotlin code do?<br>class Box&lt;T, U&gt;(val first: T, val second: U)
It defines a generic class Box that holds two values: one of type T and one of type U. You can create Box&lt;Int, String&gt; or Box&lt;Double, Boolean&gt;.
Click to reveal answer
intermediate
Can multiple type parameters have constraints in Kotlin? How?
Yes. You can restrict each type parameter with 'where' clauses or inline constraints, like <T : Number, U : Comparable<U>> to require T to be a Number and U to be comparable.
Click to reveal answer
How do you declare a Kotlin class with two type parameters?
Aclass MyClass<T; U>
Bclass MyClass<T U>
Cclass MyClass<T & U>
Dclass MyClass<T, U>
What is the purpose of multiple type parameters in Kotlin generics?
ATo allow a generic type to work with multiple types at once
BTo restrict a generic type to only one type
CTo make the code run faster
DTo avoid using generics
Which of these is a valid Kotlin function declaration with two type parameters?
Afun <T U> combine(a: T, b: U): String
Bfun <T, U> combine(a: T, b: U): String
Cfun <T; U> combine(a: T, b: U): String
Dfun <T & U> combine(a: T, b: U): String
How do you add constraints to multiple type parameters in Kotlin?
Afun <T where Number, U where Comparable> doSomething()
Bfun <T Number, U Comparable> doSomething()
Cfun <T : Number, U : Comparable<U>> doSomething()
Dfun <T & Number, U & Comparable> doSomething()
What will this code print?<br>val box = Box(10, "hello")<br>println(box.first)<br>println(box.second)
A10<br>hello
Bhello<br>10
CError
Dnull<br>null
Explain how to declare and use a Kotlin generic class with two type parameters.
Think about a class that holds two different types of values.
You got /3 concepts.
    Describe why multiple type parameters are useful in Kotlin programming.
    Consider how pairs or maps use two types.
    You got /4 concepts.