Ad space (banner)
๐ŸŽฏKotlin Lessons
Lesson 51 / 68

Writing Generic Functions

In this lesson you will learn how to write generic functions in Kotlin, so one function can work with several types. This is for anyone searching for "Kotlin generics how to use".

Generics (<T>) let you write a function that works with any type instead of committing to one. That is useful when you want the same logic for numbers and for strings.

The sample code defines fun <T : Comparable<T>> larger(a: T, b: T): T, so both the numeric larger(3, 7) and the string larger("apple", "banana") go through the same function. The T : Comparable<T> constraint is what restricts it to comparable types.

A common stumbling block for beginners is why the constraint is needed at all. With a bare T and no constraint there is no guarantee that comparison operators are available, and a constraint such as Comparable raises the safety.

In real-world development, generics are widely used to raise reusability and save writing the same method again for every type.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Kotlin directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)