How to Create Extension on Collection in Kotlin
In Kotlin, you create an extension on a collection by defining an
extension function with the collection type as the receiver. Use the syntax fun CollectionType.functionName() to add new behavior to collections like List or Set without modifying their original code.Syntax
To create an extension function on a collection, write fun followed by the collection type as the receiver, then the function name and body.
- fun: keyword to declare a function
- CollectionType: the type you want to extend, e.g.,
List<T>,Set<T>, orCollection<T> - functionName: your new function's name
- (): parentheses for parameters (optional)
- { }: function body with your code
kotlin
fun <T> Collection<T>.customFunction() {
// function body
}Example
This example adds an extension function secondOrNull() to List<T> that returns the second element or null if it doesn't exist.
kotlin
fun <T> List<T>.secondOrNull(): T? {
return if (this.size >= 2) this[1] else null
}
fun main() {
val numbers = listOf(10, 20, 30)
val emptyList = listOf<Int>()
println(numbers.secondOrNull()) // Output: 20
println(emptyList.secondOrNull()) // Output: null
}Output
20
null
Common Pitfalls
Common mistakes when creating collection extensions include:
- Not using
thisto refer to the collection inside the function. - Forgetting to make the function
genericwith<T>when needed. - Trying to modify immutable collections inside the extension (extensions can't change the original collection).
Example of a wrong and right way:
kotlin
// Wrong: missing generic type and incorrect receiver fun List<*>.secondElement() = this[1] // Error: List requires type parameter // Right: generic extension function fun <T> List<T>.secondElement(): T? = if (this.size > 1) this[1] else null
Quick Reference
| Concept | Description |
|---|---|
| fun | Keyword to declare a function |
| Generic type parameter for collections | |
| Collection | Receiver type to extend (e.g., List |
| functionName() | Name of your extension function |
| this | Refers to the collection inside the function |
| Return type | Specify if function returns a value or null |
Key Takeaways
Use fun with the collection type as receiver to create extension functions.
Make extension functions generic with to work with any element type.
Use this inside the function to access the collection elements.
Extensions cannot modify the original collection if it is immutable.
Test your extension with different collection instances to ensure safety.