October 2019
Intermediate to advanced
434 pages
11h 54m
English
You may not want to rely on top-level functions and properties in cases where you would ideally like to scope, or associate, a function or value with a particularl class. This might be the case for things such as factory methods or scoped constants. For these situations, we can rely on companion objects to achieve that type of relationship.
Let's say that we want to provide constants to represent the result state of a page. We could achieve this using companion objects, like so:
class AuthScreen { companion object { const val RESULT_AUTHENTICATED = 0 const val RESULT_ERROR = 1 }}
By defining the constants within the companion object, we avoid polluting the global namespace with top-level properties. We will then be able ...
Read now
Unlock full access