CodeBlanks Logo Icon CodeBlanks

companion extensions

Learn to add extensions to companion objects.

companion extension

A companion extension adds an extension function to a class's companion object. It is written as fun ClassName.Companion.method(). It is called by class name like a static method.

Example: fun User.Companion.default(): User { return User("guest") }. This extension is called as User.default(). You can add factory methods and helpers without changing the class's own companion object. It is especially useful when you cannot touch the class source. Companion is the default name of the companion object.

The default factory method

A companion extension can add a factory method to a class from outside. The Companion reference is written as the receiver type.

Example: fun User.Companion.default(): User { return User("guest") }. Calling User.default() returns User("guest"). This is a way to add factory methods without changing the class definition. It is especially useful for third-party library classes. Inside a companion extension, this refers to the companion object.

Practice The User.Companion.default extension

Define a class User(val name: String) with a companion object block (it may be empty). Define an extension function fun User.Companion.default(): User whose body returns User("guest"). In main print User.default().name with println.

Starter code

Main.kt
// Define the User class with a class-level singleton block
// Companion reference and default extension definition
// call default in main and print name

Sample solution

Main.kt
class User(val name: String) {
    companion object
}

fun User.Companion.default(): User {
    return User("guest")
}

fun main() {
    println(User.default().name)
}

Expected output

guest

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How is a <strong>companion extension</strong> called?

  • Through a class instance
  • Only from a subclass
  • Directly via the class name Correct answer
  • With a new object

Explanation: A companion extension is called directly via the class name.

2 Match the companion extension parts

Term Meaning
ClassName.Companion Receiver reference
fun User.Companion.default Extension definition
User.default() Call
User("guest") Return value

3 Complete the companion extension definition

Question
fun User.____.default(): User {
    return User("guest")
}
Answer
fun User.Companion.default(): User {
    return User("guest")
}

Explanation: The Companion reference points to the companion object.

All lessons in Intermediate