Kotlin has no static keyword. Put the method in a companion object: class User { companion object { fun of(name: String) = … } }, then call it on the class name, User.of("Ada"). For a helper that doesn't belong to any class, write a top-level function outside every class. Add @JvmStatic only when Java code should call it as a real static method.
In Java, static marks a method or field that belongs to the class rather than to an instance. Kotlin splits that job in three: functions and properties at the top level of a file, a companion object inside a class for members you call on the class name, and object declarations for singletons. The sections below show each one, the difference between object and companion object, the Kotlin form of a static initializer block, what @JvmStatic changes for Java callers, and extension functions that you call like static methods, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.
1A companion object: ClassName.method()Recommended
A companion object { … } block inside a class holds the members you would mark static in Java. You call them on the class name, with no instance: Temperature.fromCelsius(100.0). A var in the companion is the Kotlin form of a static variable, one copy shared by the whole class. Because the companion sits inside the class, it can call a private constructor, which makes it the usual home for factory methods. Writing static fun out of Java habit fails here with Syntax error: Expecting member declaration.
import java.util.Locale class Temperature private constructor(val celsius: Double) { override fun toString() = "%.1f C".format(Locale.US, celsius) companion object { // Like a Java static field: one copy for the whole class var created = 0 private set // Like Java static methods: called on the class name fun fromCelsius(c: Double): Temperature { created++ return Temperature(c) } fun fromFahrenheit(f: Double) = fromCelsius((f - 32) * 5 / 9) } } fun main() { val boiling = Temperature.fromCelsius(100.0) val body = Temperature.fromFahrenheit(98.6) println(boiling) println(body) println("created: ${Temperature.created}") // The companion is a real object, named Companion by default println(Temperature.Companion.created) val factory = Temperature.Companion println(factory.fromCelsius(-40.0)) println("created: ${Temperature.created}") }
Output
Both factories run without an instance, and fromFahrenheit(98.6) prints 37.0 C. The counter is shared: created: 2 after two calls, created: 3 after the third. private set lets only the companion change it. Temperature.Companion names the companion itself, which is how you hand it around as a value (and how Java reaches it, see section 5). Outside the class, Temperature(5.0) fails with Cannot access 'constructor(celsius: Double): Temperature': it is private in 'Temperature'.
2Top-level functions and properties
Many Java classes exist only to hold static helpers: StringUtils, MathUtils. In Kotlin you skip the class and write the function at the top level of the file. Code in the same package calls it by name; other packages import it first. Top-level val and var properties work as static fields, and private keeps them visible only in this file. Reach for a companion object when the function belongs to one class (a factory, a parser for that type); otherwise a top-level function is the simpler choice.
import java.lang.reflect.Modifier import kotlin.reflect.jvm.javaMethod // A top-level function: no class, no object fun slugify(title: String): String = title.lowercase() .split(Regex("[^a-z0-9]+")) .filter { it.isNotEmpty() } .joinToString("-") // Top-level properties work like static fields val appName = "Notes" private var lastId = 0 fun nextId(): Int = ++lastId fun main() { println(slugify("How to Create a Static Method?")) println(slugify(" Kotlin 2.4: What's New ")) println("$appName ${nextId()} ${nextId()}") // On the JVM it is a static method of a class named after the file val method = ::slugify.javaMethod!! println(method.declaringClass.name) println(Modifier.isStatic(method.modifiers)) }
Output
slugify is called with no class in front of it, and the private counter gives Notes 1 2. The last two lines look under the hood: the compiler puts top-level functions in a class named after the file, here MainKt for Main.kt, as static methods (true). Java code calls it as MainKt.slugify(…); the file annotation @file:JvmName("Slugs") renames that class.
3object vs companion object
An object Registry { … } declaration is a class with exactly one instance, created the first time you use it: Kotlin's built-in singleton. You call its members as Registry.add(…), which looks like a static call. A companion object is the same kind of object, tied to a class: it can reach the class's private members, you call it through the class name, and there is at most one per class. Because both are real objects, not a set of static members, they can implement interfaces and be passed as values. That is the answer to "why a companion object instead of static".
interface Parser<T> { fun parse(text: String): T } // object: a singleton with its own name, created on first use object Registry { private val names = mutableListOf<String>() init { println("Registry created") } fun add(name: String) { names += name } fun all(): List<String> = names } // companion object: belongs to a class, can call its private constructor class Color private constructor(val hex: String) { override fun toString() = "Color($hex)" companion object : Parser<Color> { override fun parse(text: String): Color { val hex = text.trim().removePrefix("#").lowercase() Registry.add(hex) return Color(hex) } } } // A companion is a value, so it can go where a Parser is expected fun <T> parseAll(parser: Parser<T>, items: List<String>): List<T> = items.map { parser.parse(it) } fun main() { println("start") println(Color.parse("#FF8800")) println(parseAll(Color, listOf(" #00ff00", "#0000FF"))) println(Registry.all()) println(Color is Parser<*>) }
Output
Registry created prints after start: the object is built when Color.parse first touches it, not when the program starts. The companion implements Parser, so parseAll(Color, …) passes the class name where a parser is expected, which no Java static method can do. All three colors end up in the one shared list. Use object for something that stands on its own (a registry, a cache, a set of defaults) and a companion for members that belong to one class.
4A static initializer block: init in the companion
Java's static { … } block becomes an init block inside the companion object. It runs once, when the class is first used: by a call on the companion or by creating the first instance, whichever comes first. It can assign val properties declared without a value. When the setup is a single expression, a plain initializer (val settings = load()) does the same job without the block.
class Config { init { println("instance init") } companion object { val settings: Map<String, String> // Kotlin's static block: runs once, when the class is first used init { println("companion init") settings = mapOf("mode" to "dark", "lang" to "en") } fun get(key: String): String = settings[key] ?: "?" } } fun main() { println("main starts") Config() Config() println(Config.get("mode")) println(Config.get("lang")) }
Output
companion init prints once, before the first instance init, and never again: not for the second instance and not for the get calls. That matches a Java static block, which runs when the class is loaded. A standalone object works differently, as section 3 showed: its init waits until the object itself is first used. For a value that is costly to build and may never be needed, val table by lazy { … } in the companion delays the work until the first read.
5@JvmStatic: real static methods for Java callers
From Kotlin, Plain.create() looks static, but on the JVM it isn't: the compiler makes a nested class Plain$Companion and puts create there as an instance method. Java code has to write Plain.Companion.create(). Annotating the function with @JvmStatic adds a real static method to the outer class as well, so Java can call Annotated.create(). Kotlin callers see no difference. The program below asks the JVM, through reflection, where each create ended up.
import java.lang.reflect.Modifier class Plain { companion object { fun create() = Plain() } } class Annotated { companion object { @JvmStatic fun create() = Annotated() } } fun describe(cls: Class<*>) { val found = cls.declaredMethods.filter { it.name == "create" } if (found.isEmpty()) println("${cls.name}: no create()") for (m in found) { val kind = if (Modifier.isStatic(m.modifiers)) "static" else "instance" println("${cls.name}: $kind create()") } } fun main() { describe(Plain::class.java) describe(Plain.Companion::class.java) describe(Annotated::class.java) describe(Annotated.Companion::class.java) }
Output
Without the annotation, Plain has no create() at all; the only one is the instance method on Plain$Companion. With it, Annotated gains a static create() that forwards to the companion, which keeps its own copy. Add @JvmStatic when Java code or a Java framework needs a true static method (a main in a companion, a factory method a Java library calls); in pure Kotlin code it changes nothing. For fields, const val and @JvmField play the same role, covered in define constants.
6Static extension functions on a companion
An extension function normally needs an instance: fun String.shout() is called as "hi".shout(). To add something you call on the type name, like a static method, extend its companion: fun Money.Companion.parse(text: String) is called as Money.parse(…). The class must have a companion, even an empty one (companion object with no body is enough). Kotlin's Int and String have companions, so they take these extensions too.
class Money(val cents: Long) { override fun toString() = "$" + "%d.%02d".format(cents / 100, cents % 100) // An empty companion is enough to hang extensions on companion object } // Extensions on the companion are called like static methods fun Money.Companion.parse(text: String): Money { val (whole, frac) = text.removePrefix("$").split(".") return Money(whole.toLong() * 100 + frac.toLong()) } val Money.Companion.ZERO: Money get() = Money(0) // Built-in types have companions too fun Int.Companion.parseOrZero(s: String): Int = s.toIntOrNull() ?: 0 fun String.Companion.dashes(n: Int): String = "-".repeat(n) fun main() { println(Money.parse("$12.50")) println(Money.ZERO) println(Int.parseOrZero("42")) println(Int.parseOrZero("x")) println(String.dashes(10)) println(Int.MAX_VALUE) }
Output
Money.parse("$12.50") and Money.ZERO read like members of Money, though they are declared outside it; the same goes for Int.parseOrZero next to the built-in Int.MAX_VALUE. Remove the companion object line from Money and the compiler stops with Unresolved reference 'Companion'. That is also why Java classes such as java.io.File can't get static extensions: they have no companion to extend.
7Which should you use?
| Method | Kotlin call | Java call | Best for |
|---|---|---|---|
| companion object { fun f() } | Type.f() | Type.Companion.f() | Factories and helpers that belong to one class |
| fun f() at top level | f() | MainKt.f() | Utilities that need no class |
| object Name { fun f() } | Name.f() | Name.INSTANCE.f() | Singletons and shared state |
| @JvmStatic fun f() in a companion | Type.f() | Type.f() | Classes that Java code calls |
| fun Type.Companion.f() | Type.f() | Static method of the file class | Static-style helpers for a type you don't own |
| companion object { init { } } | Runs once | Like static { } | One-time setup of a class |
Frequently asked questions
Does Kotlin have static methods?
Not as a keyword: there is no static in Kotlin, and static fun fails with Syntax error: Expecting member declaration. You get the same effect from a function in a companion object, called as ClassName.function(), from a top-level function outside any class, or from a function in an object declaration. On the JVM, top-level functions and @JvmStatic members compile to real static methods.
What is the difference between object and companion object in Kotlin?
Both are singletons. object Name stands on its own, you reach it by its name, and it is created the first time you use it. A companion object lives inside a class, you reach its members through the class name, it can use the class's private members, a class has at most one, and it is initialized when the class is first used, like a Java static block.
Why does Kotlin use companion objects instead of static?
A companion is a real object, so it can implement an interface, be passed as a value (parseAll(Color, items)) and carry extension functions, none of which Java static members can do. For plain helpers Kotlin offers top-level functions, so most of the jobs static did in Java don't need a class at all.
When should I use @JvmStatic?
Only when Java code, or a Java framework, needs to call a companion or object member as a real static method. Without it, Java writes MyClass.Companion.create() for a companion and MyObject.INSTANCE.create() for an object; with it, MyClass.create() works. Kotlin callers see no change, so code used only from Kotlin doesn't need the annotation.
How do I declare a static variable in Kotlin?
Put a var in the companion object (companion object { var count = 0 }) or at the top level of the file. Either one has a single copy shared by everything that uses it. Add private set to let only the companion change it. For constant values use const val, covered in the define-constants article.
Can I call a companion object function on an instance?
No. Unlike Java, which allows obj.staticMethod(), Kotlin only lets you reach companion members through the class name. Foo().make() fails with Unresolved reference 'make' on receiver of type 'Foo'. Inside the class's own methods you can call companion members without a prefix.
Can I add a static extension function to a Java class?
No. A static-style extension is declared on the companion, fun Type.Companion.f(), and Java classes such as java.io.File have no companion, so fun File.Companion.temp() fails with Unresolved reference 'Companion'. Write a top-level function instead, or a function in your own object.
Run it yourself
Open any of these in the full Kotlin editor to tweak, run and share.
Kotlin playground