Last Updated:

Delegate classes in Kotlin

Delegated properties are class fields (or global variables) that will be accessed by the code of a special delegate class. The simplest example of using delegated properties would look like this:

All this delegate class does is trim a string (discards leading and trailing spaces) written to a variable. Further, if you declare a variable using this delegate class, the rows written to it will automatically be trimmed:

In Android, delegated properties are very useful for accessing options using SharedPreferences. Simply create the following extension function for the SharedPreferences class:

Declare a variable that will be bound to the desired option, and just write/read the values. They will be automatically saved to the settings file: