What does 'by' keyword do in Kotlin?

While developing for android I sometimes come across something that looks like this:

var someModel: someViewModel by notNullAndObservable { vm ->

I don't understand what the significance of the by keyword is.


  • In the Kotlin reference you will find two uses for by, the first being Delegated Properties which is the use you have above:

    There are certain common kinds of properties, that, though we can implement them manually every time we need them, would be very nice to implement once and for all, and put into a library. Examples include lazy properties: the value gets computed only upon first access, observable properties: listeners get notified about changes to this property, storing properties in a map, not in separate field each.

    Here you delegate the getter/setter to another class that does the work and can contain common code. As another example, some of the dependency injectors for Kotlin support this model by delegating the getter to receiving a value from a registry of instances managed by the dependency injection engine.

    And Interface/Class delegation is the other use:

    The Delegation pattern has proven to be a good alternative to implementation inheritance, and Kotlin supports it natively requiring zero boilerplate code. A class Derived can inherit from an interface Base and delegate all of its public methods to a specified object

    Here you can delegate an interface to another implementation so the implementing class only needs to override what it wants to change, while the rest of the methods delegate back to a fuller implementation.

    A live example would be the Klutter Readonly/Immutable collections where they really just delegate the specific collection interface to another class and then override anything that needs to be different in the readonly implementation. Saving a lot of work not having to manually delegate all of the other methods.

    Both of these are covered by the Kotlin language reference, start there for base topics of the language.