From the course: Kotlin Essential Training: Object-Oriented and Async Code

Unlock the full course today

Join today to access over 24,900 courses taught by industry experts.

Companion objects

Companion objects

- [Instructor] Kotlin does not have a static keyword, instead relying on things like top level and extension functions to achieve similar semantics. However, sometimes it's still useful to be able to scope properties or methods to a particular type. Companion objects provide a mechanism for mimicking the semantics of static in Java and can be a useful tool for code organization or interoperability with Java. Fundamentally, a companion object is an object declaration within a class. So, we are going to create a new class called SearchController and within that SearchController class we are going to have a private mutable variable called query that holds a current search query string. Now, what if we wanted to create some kind of factory method for creating a new instance of SearchController, we could just create a top level function, but then that function might have to be public or internal, possibly polluting the global name…

Contents