WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Kotlin · Advanced · question 42 of 100

How do you define and use a generic function or class in Kotlin? Provide examples.?

📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

Kotlin allows you to define generic functions and classes which can operate on different types of data without the need for duplication of code. In Kotlin, generic functions and classes are defined using angle brackets (‘<‘ and ‘>‘).

To define a generic function, use the ‘<T>‘ notation before the function name. ‘T‘ is a placeholder for the generic type. You can use any letter or word (as long as it begins with a capital letter) as a placeholder for the generic type.

Example of a generic function:

fun <T> printArray(array: Array<T>) {
    for (element in array) {
        println(element)
    }
}

In the above example, the function ‘printArray‘ takes an array of any type ‘T‘ and prints each element on a new line.

To call the ‘printArray‘ function, you must specify the type of the array:

val intArray = arrayOf(1, 2, 3)
printArray(intArray) // prints 1, 2, 3 on new lines

val stringArray = arrayOf("foo", "bar", "baz")
printArray(stringArray) // prints foo, bar, baz on new lines

To define a generic class, use the same ‘<T>‘ notation before the class name. You can then use ‘T‘ as the type for class properties and functions.

Example of a generic class:

class Stack<T> {
    private val stack = mutableListOf<T>()

    fun push(element: T) {
        stack.add(element)
    }

    fun pop(): T? {
        if (stack.isEmpty()) return null
        return stack.removeAt(stack.size - 1)
    }
}

In the above example, the ‘Stack‘ class is defined as a generic class which can hold any type of data. The class has two functions: ‘push‘ adds an element to the top of the stack, and ‘pop‘ removes and returns the top element from the stack.

To use the ‘Stack‘ class, you must specify the type of data it will hold:

val intStack = Stack<Int>()
intStack.push(1)
intStack.push(2)
intStack.pop() // returns 2
intStack.pop() // returns 1

val stringStack = Stack<String>()
stringStack.push("foo")
stringStack.push("bar")
stringStack.pop() // returns "bar"
stringStack.pop() // returns "foo"

In conclusion, generic functions and classes in Kotlin allow you to write code that can work with different types of data without duplicating code. The generic type is specified using angle brackets (‘<‘ and ‘>‘) and can be used in function parameters, return types, class properties, and functions.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Kotlin interview — then scores it.
📞 Practice Kotlin — free 15 min
📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

All 100 Kotlin questions · All topics