Bird
Raised Fist0
Kotlinprogramming~10 mins

Generic function declaration in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Generic function declaration
Start
↓
Declare function with <T>
↓
Use T as parameter type
↓
Use T as return type
↓
Call function with specific type
↓
Function executes with that type
↓
End
This flow shows how a generic function is declared with a type placeholder T, used in parameters and return type, then called with a specific type.
Execution Sample
Kotlin
fun <T> identity(value: T): T {
    return value
}

val result = identity(42)
This code declares a generic function identity that returns the same value it receives, then calls it with an Int.
Execution Table
StepActionEvaluationResult
1Declare generic function identity with type parameter TT is a placeholder for any typeFunction ready to use with any type
2Call identity with value 42T is inferred as IntFunction called with value=42 of type Int
3Inside function: return valueReturn 42Returns 42
4Assign return to resultresult = 42result holds Int value 42
💡 Function completes after returning the input value
Variable Tracker
VariableStartAfter CallFinal
valueN/A4242
resultN/AN/A42
Key Moments - 3 Insights
Why do we write <T> before the function name?
The <T> declares a generic type parameter T that can be used inside the function. This is shown in execution_table step 1 where T is a placeholder.
How does Kotlin know what type T is when calling the function?
Kotlin infers T from the argument type at the call site, as shown in step 2 where T is inferred as Int because 42 is an Int.
Can the function return a different type than the input?
No, because the return type is T, the same as the input parameter type, so it returns the same type it receives (step 3).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table step 2, what type is T inferred as when calling identity(42)?
AInt
BString
CAny
DDouble
💡 Hint
Check the 'Evaluation' column in step 2 where T is inferred as Int.
At which step does the function return the input value?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look for the step where the function returns the value inside the function.
If we call identity("hello"), how would the variable 'value' change in variable_tracker?
Avalue would be 42
Bvalue would be "hello"
Cvalue would be null
Dvalue would be Int
💡 Hint
Refer to variable_tracker where 'value' holds the input passed to the function.
Concept Snapshot
Generic function declaration syntax:
fun <T> functionName(param: T): T {
    // use T as type
}

- <T> declares a type parameter T
- T can be used as parameter and return type
- Kotlin infers T from the argument when called
- Enables writing flexible, reusable functions
Full Transcript
This visual trace shows how a generic function is declared and used in Kotlin. First, the function identity is declared with a generic type parameter T. This means T can be any type. When calling identity(42), Kotlin infers T as Int because 42 is an Int. Inside the function, the value parameter has type T, so it is Int here. The function returns the same value it received. The result variable receives the returned value 42. The variable tracker shows how 'value' and 'result' change during execution. Key moments clarify why <T> is needed, how Kotlin infers types, and why the return type matches the input type. The quiz questions test understanding of type inference, return step, and variable values when calling with different types.

Practice

(1/5)
1. What is the purpose of declaring a generic function in Kotlin using <T> before the function name?
easy
A. To declare a function that returns a string only
B. To restrict the function to only work with integers
C. To make the function run faster
D. To allow the function to work with any type specified when called

Solution

  1. Step 1: Understand generic type declaration

    Declaring <T> before a function name means the function can accept any type as input.
  2. Step 2: Purpose of generic functions

    This makes the function reusable for different data types without rewriting it for each type.
  3. Final Answer:

    To allow the function to work with any type specified when called -> Option D
  4. Quick Check:

    Generic functions = reusable for any type [OK]
Hint: Generic <T> means any type can be used [OK]
Common Mistakes:
  • Thinking generic restricts to one type
  • Confusing generic with function overloading
  • Assuming generic improves speed automatically
2. Which of the following is the correct syntax to declare a generic function named printItem that takes a parameter of any type T in Kotlin?
easy
A. fun <T> printItem(item: T) { println(item) }
B. fun printItem<T>(item) { println(item) }
C. fun printItem(T item) { println(item) }
D. fun printItem(item: <T>) { println(item) }

Solution

  1. Step 1: Identify correct generic syntax

    In Kotlin, generic type parameters are declared before the function name using <T>.
  2. Step 2: Check parameter declaration

    The parameter must specify its type as T, so item: T is correct.
  3. Final Answer:

    fun <T> printItem(item: T) { println(item) } -> Option A
  4. Quick Check:

    Generic syntax = <T> before function name [OK]
Hint: Generic type <T> goes before function name [OK]
Common Mistakes:
  • Placing <T> after function name
  • Not specifying parameter type as T
  • Using parentheses incorrectly around <T>
3. What will be the output of the following Kotlin code?
fun <T> identity(value: T): T {
    return value
}

fun main() {
    println(identity(123))
    println(identity("Hello"))
}
medium
A. 123 123
B. 123 Hello
C. Hello Hello
D. Compilation error

Solution

  1. Step 1: Understand the generic function behavior

    The function identity returns the same value it receives, regardless of type.
  2. Step 2: Trace the calls in main()

    Calling identity(123) returns 123, and identity("Hello") returns "Hello".
  3. Final Answer:

    123 Hello -> Option B
  4. Quick Check:

    Generic function returns input value [OK]
Hint: Generic function returns input as is [OK]
Common Mistakes:
  • Expecting type conversion
  • Thinking output repeats first call
  • Assuming compilation error due to mixed types
4. Identify the error in this Kotlin generic function declaration:
fun printValue<T>(value: T) {
    println(value)
}
medium
A. Generic type parameter <T> must be declared before the function name
B. Parameter type cannot be generic
C. Function must return a value
D. println cannot print generic types

Solution

  1. Step 1: Check generic syntax rules

    In Kotlin, generic type parameters must be declared before the function name, not after.
  2. Step 2: Analyze the given code

    The code declares printValue<T>, which is incorrect syntax.
  3. Final Answer:

    Generic type parameter <T> must be declared before the function name -> Option A
  4. Quick Check:

    Generic <T> goes before function name [OK]
Hint: Place <T> before function name, not after [OK]
Common Mistakes:
  • Putting <T> after function name
  • Assuming generic parameters go in parentheses
  • Thinking generic functions must return a value
5. You want to write a generic function swap that swaps two elements in a mutable list at given indices. Which of the following is the correct Kotlin function declaration and implementation?
hard
A. fun swap<T>(list: MutableList<T>, i: Int, j: Int) { val temp = list[i] list[i] = list[j] list[j] = temp }
B. fun <T> swap(list: List<T>, i: Int, j: Int) { val temp = list[i] list[i] = list[j] list[j] = temp }
C. fun <T> swap(list: MutableList<T>, i: Int, j: Int) { val temp = list[i] list[i] = list[j] list[j] = temp }
D. fun swap(list: MutableList<Any>, i: Int, j: Int) { val temp = list[i] list[i] = list[j] list[j] = temp }

Solution

  1. Step 1: Correct generic syntax and parameter types

    The generic type parameter <T> must be declared before the function name. The list must be mutable to allow swapping.
  2. Step 2: Verify implementation correctness

    The function swaps elements at indices i and j using a temporary variable, which is correct.
  3. Final Answer:

    fun <T> swap(list: MutableList<T>, i: Int, j: Int) { val temp = list[i]; list[i] = list[j]; list[j] = temp } -> Option C
  4. Quick Check:

    Generic swap needs <T> before name and MutableList<T> [OK]
Hint: Use <T> before function and MutableList<T> for mutability [OK]
Common Mistakes:
  • Putting <T> after function name
  • Using immutable List instead of MutableList
  • Using MutableList<Any> losing type safety
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