Bird
Raised Fist0
Kotlinprogramming~10 mins

Multiple type parameters in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Multiple type parameters
Define generic class/function with <T, U>
↓
Use T and U as types inside
↓
Create instance with specific types
↓
Access members using T and U types
↓
Use or return values of types T and U
This flow shows how Kotlin uses multiple type parameters to create flexible generic classes or functions that work with different types.
Execution Sample
Kotlin
class Pair<T, U>(val first: T, val second: U)

fun main() {
  val p = Pair<Int, String>(1, "one")
  println("${p.first} and ${p.second}")
}
This code defines a generic Pair class with two type parameters and creates an instance with Int and String types.
Execution Table
StepActionEvaluationResult
1Define class Pair with type parameters T and UT and U are placeholdersClass ready to use with any types
2Call main functionStart executionEnter main
3Create Pair instance with T=Int, U=StringPair<Int, String>(1, "one")p.first = 1, p.second = "one"
4Print p.first and p.secondprintln("${p.first} and ${p.second}")Output: 1 and one
5End of mainProgram finishesExecution stops
💡 Program ends after printing the pair values
Variable Tracker
VariableStartAfter Step 3After Step 4Final
p.firstundefined111
p.secondundefined"one""one""one"
Key Moments - 3 Insights
Why do we write <T, U> in the class definition?
The <T, U> declares two type placeholders so the class can hold two different types. See execution_table step 1 where the class is defined with these placeholders.
How does Kotlin know what types T and U are?
When creating the instance (step 3), we specify the actual types Int and String, so Kotlin replaces T with Int and U with String.
What happens if we swap the types when creating Pair?
Swapping types changes what p.first and p.second hold. For example, Pair<String, Int>("one", 1) would reverse their types. This is shown by the type parameters in step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what is the type of p.second?
AInt
BString
CDouble
DBoolean
💡 Hint
Check the 'Evaluation' column at step 3 where Pair is created
At which step does the program print the output?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look for the 'Print' action in the 'Action' column
If we change Pair<Int, String> to Pair<String, Int>, what will p.first be at step 3?
A"one"
B1
Cnull
DCompilation error
💡 Hint
Refer to the 'variable_tracker' and how type parameters map to values
Concept Snapshot
Multiple type parameters allow defining generic classes or functions with more than one type placeholder.
Syntax: class Pair<T, U>(val first: T, val second: U)
Use: Specify types when creating instances, e.g., Pair<Int, String>(1, "one")
This enables flexible, reusable code that works with different type combinations.
Full Transcript
This example shows how Kotlin uses multiple type parameters in a generic class called Pair. The class is defined with two placeholders, T and U, which represent any types. When we create an instance of Pair, we specify the actual types, like Int and String. The program then stores values of these types in the first and second properties. The execution table traces each step: defining the class, starting main, creating the Pair instance, printing the values, and ending the program. The variable tracker shows how p.first and p.second get their values. Key moments clarify why we use <T, U>, how Kotlin knows the types, and what happens if we swap them. The quiz tests understanding of types at different steps and the effect of changing type parameters. This helps beginners see how multiple type parameters work in practice.

Practice

(1/5)
1. What does it mean when a Kotlin function has <T, U> before its name?
easy
A. The function is limited to only one type parameter named T or U.
B. The function can only accept types T or U but not both at the same time.
C. The function uses two different type parameters, T and U, to work with multiple types.
D. The function automatically converts types T and U to String.

Solution

  1. Step 1: Understand type parameters in Kotlin

    Type parameters like <T, U> allow a function to accept multiple types, making it flexible.
  2. Step 2: Interpret the meaning of <T, U>

    Having <T, U> means the function can work with two different types, T and U, independently.
  3. Final Answer:

    The function uses two different type parameters, T and U, to work with multiple types. -> Option C
  4. Quick Check:

    Multiple type parameters = flexible function types [OK]
Hint: Multiple type parameters mean multiple flexible types [OK]
Common Mistakes:
  • Thinking it limits to only one type at a time
  • Assuming automatic type conversion happens
  • Confusing type parameters with actual types
2. Which of the following is the correct syntax to declare a Kotlin function with two type parameters named T and U?
easy
A. fun myFunction(param1: T, param2: U) {}
B. fun myFunction(param1: T, param2: U) {}
C. fun myFunction(param1: T, param2: U) {}
D. fun myFunction(param1: T, param2: U) {}

Solution

  1. Step 1: Recall Kotlin generic function syntax

    Type parameters are declared immediately after the fun keyword inside angle brackets, separated by commas.
  2. Step 2: Check each option's syntax

    fun myFunction(param1: T, param2: U) {} correctly uses <T, U> after fun and before the function name, matching Kotlin syntax.
  3. Final Answer:

    fun <T, U> myFunction(param1: T, param2: U) {} -> Option A
  4. Quick Check:

    Type parameters go after fun with commas [OK]
Hint: Type parameters come right after fun, separated by commas [OK]
Common Mistakes:
  • Missing comma between type parameters
  • Placing type parameters after function name
  • Putting type parameters after parameter list
3. What is the output of this Kotlin code?
fun <T, U> pairToString(pair: Pair<T, U>): String {
    return "${pair.first} and ${pair.second}"
}

fun main() {
    val result = pairToString(Pair(10, "cats"))
    println(result)
}
medium
A. Compilation error
B. Pair(10, cats)
C. cats and 10
D. 10 and cats

Solution

  1. Step 1: Understand the function behavior

    The function takes a Pair with types T and U, then returns a string combining first and second values.
  2. Step 2: Trace the main function call

    pairToString is called with Pair(10, "cats"), so pair.first = 10 and pair.second = "cats".
  3. Final Answer:

    10 and cats -> Option D
  4. Quick Check:

    pair.first + " and " + pair.second = "10 and cats" [OK]
Hint: Read pair.first and pair.second values carefully [OK]
Common Mistakes:
  • Swapping first and second values
  • Expecting Pair's default toString output
  • Thinking it causes a compilation error
4. Identify the error in this Kotlin function declaration:
fun <T, U> combine(a: T, b: U): T {
    return b
}
medium
A. Return type T does not match returned value b of type U.
B. Missing comma between T and U in type parameters.
C. Function must return type U instead of T.
D. No error, the function is correct.

Solution

  1. Step 1: Check function return type and return statement

    The function declares return type T but returns b which is of type U.
  2. Step 2: Understand type mismatch error

    Returning U where T is expected causes a type mismatch compilation error.
  3. Final Answer:

    Return type T does not match returned value b of type U. -> Option A
  4. Quick Check:

    Return type must match returned value type [OK]
Hint: Return type must match the returned value type [OK]
Common Mistakes:
  • Ignoring type mismatch between T and U
  • Assuming Kotlin auto-converts types
  • Missing comma in type parameters (not the case here)
5. You want to create a Kotlin generic class Box that can hold two different types of items, T and U. Which of the following class declarations correctly uses multiple type parameters and allows storing and retrieving both items?
hard
A. class Box<T>(val first: T, val second: T) { fun getFirst(): T = first fun getSecond(): T = second }
B. class Box(val first: T, val second: U) { fun getFirst(): T = first fun getSecond(): U = second }
C. class Box { val first: T val second: U }
D. class Box(val first: T, val second: U) { fun getFirst(): T = first fun getSecond(): U = second }

Solution

  1. Step 1: Check correct multiple type parameter declaration

    class Box(val first: T, val second: U) { fun getFirst(): T = first fun getSecond(): U = second } declares class Box with <T, U> and constructor parameters of types T and U, which is correct.
  2. Step 2: Verify methods to retrieve both items

    class Box(val first: T, val second: U) { fun getFirst(): T = first fun getSecond(): U = second } provides getFirst() returning T and getSecond() returning U, matching stored types.
  3. Final Answer:

    class Box<T, U>(val first: T, val second: U) { fun getFirst(): T = first fun getSecond(): U = second } -> Option B
  4. Quick Check:

    Multiple type parameters with matching properties and methods [OK]
Hint: Use and matching properties for both types [OK]
Common Mistakes:
  • Using only one type parameter for both items
  • Not declaring type parameters in class header
  • Using undefined types without generics
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard