Skip to content
Tutorials Center
My learning

Topics

Lesson 53 of 134 ยท Classes and Objects

Objects and Companion Objects

Learn Kotlin object declarations, singletons, companion objects, factory functions, const val, object expressions and how they replace Java static members, with runnable code.

Kotlin has no static keyword. Where Java puts utility methods and constants in a class, Kotlin gives you something more general: the object. An object declaration creates a class and its single instance in one step. A companion object attaches such an instance to a class, so you can write Config.load() or User.create(...) without an instance. An object expression creates an anonymous one-off object on the spot.

This lesson explains all three, the order in which objects are initialized, how const val and @JvmStatic fit in, and how to choose between objects, top-level functions and companions. It builds on Classes and Properties and Constructors.

Object declarations: singletons

Write object instead of class, and Kotlin creates exactly one instance, available by the object's name:

Kotlin A singleton counter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

There is no constructor to call and no way to create a second Counter. The object is created lazily and thread-safely, the first time something uses it (the JVM's class loading guarantees that). It can have properties, functions, init blocks, a superclass and interfaces, but no constructor parameters, since nobody calls a constructor.

Objects are good for stateless helpers and for things that truly exist once: a registry, a configuration holder, a logger.

Kotlin An object that implements an interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Registry created appears after start of main: the object is initialized on first use, not at program start. An object that implements an interface can be passed anywhere that interface is expected.

An object is global state. Every part of the program sees the same instance, which makes code harder to test (you cannot swap it for a fake easily) and hides dependencies. Prefer passing dependencies as parameters, and keep objects for stateless utilities and genuinely unique things.

Companion objects

A companion object is an object declared inside a class with the companion modifier. Its members are reached through the class name, which is how Kotlin spells what other languages call static members:

Kotlin A companion object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The constructor is private, so the only way to build a Temperature is through the named factory functions in the companion. Those functions have a big advantage over constructors: they have names (ofCelsius versus ofFahrenheit), they can validate, return cached values or return a subtype, and they can fail without leaving a half-built object. A companion object can see the private members of its containing class, and the class can see the companion's.

A class has at most one companion. It can be named (companion object Factory) but usually isn't; the default name is Companion. The class name alone also refers to the companion, so Temperature and Temperature.Companion mean the same thing in an expression position.

Companions can implement interfaces

A companion is a real object, so it can implement an interface and be passed around, which Java statics cannot do:

Kotlin A companion that implements an interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Point on its own, used as a value, stands for Point.Companion, so parseAll(Point, ...) compiles and passes the companion as the parser. This is the Kotlin idiom for "the class knows how to create itself".

Companions and extension functions

You can add functions to someone else's companion from outside, with an extension on Type.Companion:

Kotlin Extending a companion object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The empty companion object is the hook that makes the extension possible. Without it, Version.Companion does not exist and the call fails.

const val, @JvmStatic and static on the JVM

Members of an object are normal instance members of that single instance. The JVM bytecode is therefore not "static" unless you ask. Two tools control this:

  • const val declares a compile-time constant. It must be a primitive or String, initialized with a literal or constant expression, and declared at the top level or inside an object or companion. The compiler inlines its value. Name it in UPPER_SNAKE_CASE.
  • @JvmStatic makes a function (or property accessor) in an object or companion also available as a real static method for Java callers. Kotlin callers see no difference.
Kotlin const val versus val

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

If you try const val startedAt = computeSomething(), the compiler rejects it with a message that a const initializer must be a compile-time constant. Use plain val for anything computed.

Object expressions: anonymous objects

An object expression creates an object without declaring a named class. It is the Kotlin version of an anonymous inner class and can extend a class or implement interfaces. It may also capture variables from the surrounding code:

Kotlin Anonymous objects capture their surroundings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Unlike Java's anonymous classes, an object expression can modify captured var variables (here clicks). The second case, a bare object { ... }, creates an unnamed type with ad-hoc properties. You can use it as a local value, as above. If you return it from a public function, its type is widened to Any and the properties disappear, so use a named class or a data class there.

For a one-method interface, a lambda with a fun interface is shorter. Reach for an object expression when you need several members or state.

Initialization order and pitfalls

An object is initialized once, on first access. A companion is initialized when its containing class is loaded. Both use the JVM's class initialization lock, so they are thread-safe, but they can also deadlock or expose half-initialized state if two objects use each other during their init blocks:

Kotlin Initialization happens on first use

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

A init prints once, however often you read it. The companion initializes before the first Widget instance is built, and each instance prints its own line.

Other things to watch for:

  • Do not put heavy work in an object's init. It runs on whichever thread touches it first, and failures there throw ExceptionInInitializerError, after which the object is unusable.
  • Companion members are not inherited. A subclass does not get its parent's companion functions through its own name; call them on the parent.
  • Prefer top-level functions for utilities. In Kotlin, fun slugify(s: String) at the top level of a file is simpler than object Strings { fun slugify(...) }. Use an object when you need to group state, implement an interface, or when the grouping gives useful names.
  • Use a companion when the function conceptually belongs to the class: factories, parsers, constants tied to the type.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does object Config { ... } declare?

    An object declaration defines a class and creates one instance of it, initialized on first access in a thread-safe way.
  2. 2. Which declaration of a constant is valid?

    const val needs a compile-time constant of primitive or String type and lives at top level or in an object or companion. A function call or a collection is not a constant.
  3. 3. How do you call a companion factory function of on class Money?

    Members of a companion object are accessed through the class name, like static members in other languages.
  4. 4. Why can a companion object be more flexible than Java's static members?

    A companion is a real object, so it can implement an interface, extend a class, and be used wherever that type is expected.
  5. 5. When is an object declaration initialized?

    Objects are created lazily when first used, and once only. The 'Registry created' line in the example printed after the start of main.

Summary

  • object declares a singleton: a class plus its single instance, created lazily and thread-safely on first access, with no constructor parameters.
  • A companion object holds what other languages call static members: factories, constants, parsers. Access them through the class name.
  • Companions are real objects: they can implement interfaces and be extended with extension functions.
  • const val is for compile-time constants of primitive or String type; @JvmStatic creates real static methods for Java callers.
  • Object expressions create anonymous one-off objects that can capture and modify local variables.
  • Treat objects as global state and prefer top-level functions for plain utilities.

Next: Nested and Inner Classes