Kotlin Object Expressions and Object Declarations
Kotlin uses the object keyword to combine "creating an object" and "declaring a class" into one.
An object expression creates an anonymous object on the spot with slight modifications to a class, without declaring a separate subclass.
An object declaration declares a globally unique object, i.e. a singleton in design patterns.
The two have similar syntax but completely different semantics; this chapter clarifies their differences.
Object expressions
An object expression is written as object : supertype { ... }; it creates and executes an anonymous object right where you write the line.
The most common use is implementing an interface, then passing the object directly to a method.
Example
// define an interface
interface
Greeter
{
fun greet
(
)
:
String
}
fun main
(
)
{
// object : Greeter creates an anonymous object implementing the Greeter interface
val runoob
=
object
:
Greeter
{
override fun greet
(
)
=
"Hello, RUNOOB"
}
println
(
runoob.
greet
(
)
)
}
The output is:
Hello, RUNOOB
An object expression can inherit a class and implement multiple interfaces at once, with supertypes separated by commas.
If the supertype has a constructor, you must pass constructor arguments to it.
Example
open
class
A
(
x
:
Int
)
{
open val y
:
Int
=
x
}
interface
B
{
fun hello
(
)
:
String
}
fun main
(
)
{
// inherit A(1) and implement B at once; A's constructor argument 1 must be passed explicitly
val ab
=
object
:
A
(
1
)
, B
{
override val y
=
15
override fun hello
(
)
=
"Runoob Tutorial"
}
println
(
ab.
y
)
println
(
ab.
hello
(
)
)
}
The output is:
15
Runoob Tutorial
If you just want a temporary object with a few fields, you can even omit the supertype and use object { ... } directly.
Example
fun main
(
)
{
// with no supertype, you directly get an anonymous object
val site
=
object
{
var name
:
String
=
"Runoob Tutorial"
var url
:
String
=
"www.runoob.com"
}
println
(
site.
name
)
println
(
site.
url
)
}
The output is:
Runoob Tutorial
www.runoob.com
Inside an object expression you can directly read and write variables from the outer scope, which is very useful in event callbacks.
Example
interface
ClickListener
{
fun onClick
(
)
}
fun countClicks
(
listener
:
ClickListener
)
{
listener.
onClick
(
)
}
fun main
(
)
{
var clickCount
=
0
// the anonymous object captures the outer clickCount variable
val listener
=
object
:
ClickListener
{
override fun onClick
(
)
{
clickCount
++
println
(
"Clicked $clickCount times"
)
}
}
countClicks
(
listener
)
countClicks
(
listener
)
}
The output is:
被点击了 1 次
被点击了 2 次
The pitfall of anonymous objects as public return types
An anonymous object can be the type of a local variable or private declaration; the compiler can see its real type, and newly added members are accessible normally.
But if you use an anonymous object as the return type of a public function or the type of a public property, its real type degrades to the declared supertype, or to Any if no supertype was declared.
Example
class
C
{
// private function: return type is the anonymous object's real type
private
fun foo
(
)
=
object
{
val x
:
String
=
"RUNOOB"
}
// public function: return type degrades to Any
fun publicFoo
(
)
=
object
{
val x
:
String
=
"RUNOOB"
}
fun bar
(
)
{
val x1
=
foo
(
)
.
x
// accessible
println
(
x1
)
// val x2 = publicFoo().x // compile error: no member x on Any
}
}
fun main
(
)
{
C
(
)
.
bar
(
)
}
The output is:
RUNOOB
Note:An anonymous object retains its full type only in local and private scopes. Once it appears as the return type of a public API, its added members are no longer accessible - this is exactly why many beginners hit "unresolved reference" errors. To expose extra members, declare a named class or interface for it.
Object declarations
Writing object at the top level or inside a class followed directly by the object name is an object declaration.
An object declaration is not an expression and cannot appear on the right side of an assignment; it declares a unique instance, so it is naturally a singleton.
Example
// object declaration: a globally unique singleton
object Site
{
var url
:
String
=
""
val name
:
String
=
"Runoob Tutorial"
}
fun main
(
)
{
val s1
=
Site
val s2
=
Site
s1.
url
=
"www.runoob.com"
println
(
s1.
url
)
println
(
s2.
url
)
println
(
s1
===
s2
)
// both refer to the same instance
}
The output is:
www.runoob.com
www.runoob.com
true
An object declaration can also inherit a class or implement an interface, making it a singleton with a supertype.
Example
interface
Formatter
{
fun format
(
value
:
String
)
:
String
}
// object declaration implements an interface, usable directly via the object name
object UpperFormatter
:
Formatter
{
override fun format
(
value
:
String
)
=
value.
uppercase
(
)
}
fun main
(
)
{
println
(
UpperFormatter.
format
(
"runoob"
)
)
}
The output is:
RUNOOB
Object declarations nested inside a class
When an object declaration is written inside another class, it does not hold an outer class instance.
Therefore it can neither access outer class instance members nor be accessed through an outer class instance; only the outer class name plus a dot can access it.
Example
class
Site
{
var name
=
"Runoob Tutorial"
object DeskTop
{
var url
=
"www.runoob.com"
// fun showName() = name // compile error: cannot access outer class instance member
}
}
fun main
(
)
{
println
(
Site.
DeskTop
.
url
)
// accessible only via the class name
}
The output is:
www.runoob.com
Note:Object declarations are not allowed inside functions. If you need to create an object on the spot in a function body, use an object expression instead. Also, since Kotlin 1.9, it also supports data object, which on toString()、equals() gives a more data-oriented semantic implementation.
Companion objects
An inner object marked with companion is a companion object; it is bound to the outer class, and its members can be accessed directly via the outer class name.
A companion object looks like static members in other languages, but at runtime it is still an instance member of a real object.
Example
class
MyClass
{
// named companion object called Factory
companion object Factory
{
fun create
(
)
:
MyClass
=
MyClass
(
)
}
}
fun main
(
)
{
val instance
=
MyClass.
create
(
)
// call directly via the class name
println
(
instance is MyClass
)
println
(
MyClass.
Factory
.
create
(
)
is MyClass
)
// can also call via the companion object's name
}
The output is:
true
true
The companion object's name can be omitted; when omitted, it is referenced by the default name Companion.
Example
class
MyClass
{
companion object
{
const
val SITE
=
"www.runoob.com"
}
}
fun main
(
)
{
val companion
=
MyClass.
Companion
println
(
companion.
SITE
)
println
(
MyClass.
SITE
)
}
The output is:
www.runoob.com
www.runoob.com
A class can have at most one companion object; the companion keyword can appear only once in a class.
Companion objects implementing interfaces
Since a companion object is a real object, it can of course implement an interface and be passed as an interface instance.
Example
interface
Factory
<
T
{fun create
(
)
:
T
}
class
MyClass
{
// companion object implements the Factory interface
companion object
:
Factory
<
MyClass
{override fun create
(
)
:
MyClass
=
MyClass
(
)
var count
=
0
}
}
fun main
(
)
{
// use the companion object as a Factory instance
val factory
:
Factory
<
MyClass
=MyClass.
Companion
val a
=
factory.
create
(
)
MyClass.
count
=
3
println
(
a is MyClass
)
println
(
MyClass.
count
)
}
The output is:
true
3
Semantic differences between object expressions and object declarations
Their syntax differs by only one colon, but initialization timing is completely different - a common point in interviews and debugging.
| Syntax | Creation timing | Number of instances | Typical use |
|---|---|---|---|
| object : A() { } object expression | created immediately when execution reaches the expression | a new instance is created on every execution | event listeners, one-off interface implementations |
| object Foo { } object declaration | lazily initialized on first access | globally unique | singletons, utility objects |
| companion object (companion object) | initialized together with the outer class | one per class, globally unique | factory methods, static-style constants |
The code below puts all three timings together; observing the output order reveals the difference.
Example
// object declaration: initialized only on first access
object Singleton
{
init
{
println
(
"Singleton initialized"
)
}
fun hello
(
)
=
"hello"
}
// companion object: initialized with the outer class
class
Holder
{
companion object
{
init
{
println
(
"Holder's companion object initialized"
)
}
}
}
fun main
(
)
{
println
(
"main starts"
)
val holder
=
Holder
(
)
// triggers Holder class initialization, companion object initializes along with it
println
(
"Created Holder instance"
)
println
(
Singleton.
hello
(
)
)
// first access, Singleton initializes only now
println
(
"Accessed Singleton"
)
println
(
holder is Holder
)
}
The output is:
main 开始
Holder 的伴生对象初始化
创建了 Holder 实例
Singleton 初始化
hello
访问了 Singleton
true
Note:Companion object initialization has the same semantics as Java's static initializer and runs whenever the outer class is initialized. Object declarations are lazy; if the program never accesses it from start to finish, its init block will never run.
Common questions
Below are the most common pitfalls with object expressions and object declarations.
| Problem | Reason | Solution |
|---|---|---|
| cannot access new members after a public function returns an anonymous object | return type degrades to supertype or Any | make it a private function, or declare a named class / interface |
| error writing an object declaration inside a function | object declarations cannot be local | use an object expression instead |
| error accessing outer class fields in a nested object | nested objects do not hold an outer class instance | pass fields as parameters, or use an inner class |
| error accessing a nested object via an outer class instance | nested objects belong to the class itself, not an instance | access via OuterClassName.ObjectName |
| Java code needs extra syntax to call companion object members | companion objects are instance members, not true static members | add the @JvmStatic annotation |