Skip to content

Kotlin Companion Object

DodaTech 1 min read

In this tutorial, you'll learn about Fix Kotlin Companion Object Not Accessible. We cover key concepts, practical examples, and best practices.

The Problem

Companion object members are not accessible from Java code as static members.

Quick Fix

Use @JvmStatic

Wrong:

class MyClass {
    companion object {
        fun create() = MyClass()
    }
}
// Java: MyClass.Companion.create()

Output:

Verbose Java access

Right:

class MyClass {
    companion object {
        @JvmStatic
        fun create() = MyClass()
    }
}
// Java: MyClass.create()

Output:

Static access from Java

Use @JvmField

Wrong:

class MyClass {
    companion object {
        val TAG = "MyClass"
    }
}
// Java: MyClass.Companion.getTAG()

Output:

Getter access

Right:

class MyClass {
    companion object {
        @JvmField
        val TAG = "MyClass"
    }
}
// Java: MyClass.TAG

Output:

Direct field access

Use const for primitives

Wrong:

companion object {
    val TIMEOUT = 5000
}
// Java: MyClass.getTIMEOUT()

Output:

Method call

Right:

companion object {
    const val TIMEOUT = 5000
}
// Java: MyClass.TIMEOUT

Output:

Compile-time constant

Prevention

  • Use @JvmStatic for methods accessed from Java
  • Use @JvmField for fields accessed from Java
  • Use const for compile-time primitive/String constants

Common Mistakes with companion object

  1. Mixing let bindings with <- bindings in do notation, producing type errors
  2. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  3. Non-exhaustive pattern matches that compile with warnings then crash at runtime

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 can't Java access companion object members as static?

Companion object members are instance members of the companion class. Use @JvmStatic to expose them as static.

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