Kotlin Companion Object
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
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- 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
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