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 - Kotlin Tutorial
From the course: Kotlin Essential Training: Object-Oriented and Async Code
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
-
-
-
Classes19m 32s
-
(Locked)
Interfaces12m 29s
-
(Locked)
Enum classes12m 13s
-
(Locked)
Data classes11m 47s
-
(Locked)
Object classes7m 9s
-
(Locked)
Sealed classes11m 42s
-
(Locked)
Companion objects6m 45s
-
(Locked)
Challenge: Create a Result type using a sealed class1m 45s
-
(Locked)
Solution: Create a Result type using a sealed class6m 13s
-
-
-
-