Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. Kotlin Dictionary
  3. object / companion object

object / companion object

The object keyword defines a singleton object, and companion object provides a way to add static members to a class.

Syntax

// Defining a singleton object
object ObjectName {
    val propertyName = value
    fun methodName() { }
}

// companion object (static members inside a class)
class ClassName {
    companion object {
        val propertyName = value
        fun methodName() { }
    }
}

Syntax Overview

SyntaxDescription
object ObjectName { }Defines a singleton object. Only one instance exists throughout the program's lifetime.
companion object { }Defines static members inside a class. Equivalent to Java's static.
companion object Name { }Defines a named companion object. The name is optional.

Sample Code

// Defining and using a singleton object
object AppConfig {
    val appName = "MyApp"
    val version = "1.0.0"
    fun printInfo() = println("$appName v$version")
}

// A class with a companion object
class Counter {
    companion object {
        private var count = 0
        fun increment() { count++ }
        fun getCount() = count
    }
}

fun main() {
    // Use the object directly without instantiation.
    AppConfig.printInfo()
    println(AppConfig.version)

    // companion object members are called via the class name.
    Counter.increment()
    Counter.increment()
    println(Counter.getCount()) // 2
}

Overview

An object declaration is a concise way to implement the singleton pattern. A single instance is created at the time of declaration and shared throughout the entire program. It is commonly used to group constants and utility functions.

A companion object defines static members tied to a class. Because Kotlin has no static keyword, a companion object is used to achieve the same effect as Java's static members. It is well suited for defining factory methods and constants.

If you find any errors or copyright issues, please .