Skip to content

Kotlin Extension Function

DodaTech 1 min read

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

  1. Using foldl instead of foldl' causing stack overflow on large lists
  2. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  3. 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

### Why is my extension function not visible?

Extension functions must be imported. Unlike member functions, they are not automatically available.

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