October 2019
Intermediate to advanced
434 pages
11h 54m
English
Using companion objects from Java can be cumbersome because of the need to reference the instance of the Companion class. This can lead to Java code that very clearly looks like it's referencing Kotlin code. We can improve this by providing an alternative name for the companion object.
In the following snippet, we've specified Factory as the name of our companion object by adding the desired name after the object keyword:
class Widget { companion object Factory { fun create() {} }}
With an alternative name specified, the generated class will have the newly specified name. We can then use that new name, Factory, in this case, to reference our companion object and any associated methods or properties:
// Main.java ...Read now
Unlock full access