August 2017
Intermediate to advanced
440 pages
10h
English
If a class has a companion object defined, then you can also define extension functions (and properties) for this companion object. To distinguish between an extension to a class and an extension to a companion object, .Companion needs to be added between the extension type and function name:
class A {
companion object {}
}
fun A.Companion.foo() { print(2) }
When it is defined, the foo method can be used as if it were defined inside the A companion object:
A.foo()
Note that we are calling this extension using the class type, not the class instance. To allow the creation of an extension function for a companion object, a companion object needs to be explicitly defined inside the class, even an empty one. Without ...
Read now
Unlock full access