Kotlin Extension Function
In this tutorial, you'll learn about Fix Kotlin Extension Function Not Resolved. We cover key concepts, practical examples, and best practices.
The Problem
Extension functions defined in one file are not visible in another file.
Quick Fix
Define extension function
Wrong:
fun String.reverse(): String = this.reversed()
// Top-level function
Output:
Not imported
Right:
fun String.reverse(): String = this.reversed()
Output:
Available everywhere if imported
Import the extension
Wrong:
// In another file:
val reversed = "hello".reverse() // Not imported
Output:
Unresolved reference
Right:
import com.example.reverse // Import extension function
Output:
Extension imported
Resolve receiver type
Wrong:
"hello".reverse() // Extension on String
Output:
Works if imported
Right:
val list = listOf(1, 2, 3)
list.second() // Extension not on List
Output:
Check receiver type
Prevention
- Define extension functions as top-level functions
- Import the function in files that use it
- Ensure the extension function's receiver type matches the call target
Common Mistakes with extension function
- Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
These mistakes appear frequently in real-world KOTLIN code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
This quick fix is part of the DodaTech Spring & JVM ecosystem series. Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro