Add syntactic sugar to your Android Preferences

  • Jonas Schmid

We open-sourced a library that allows handling Android preferences in a type-safe manner.

Learn more about our Mobile Apps service.


You can find SweetPreferences on Github.

// Define a class that will hold the preferences
class UserPreferences(sweetPreferences: SweetPreferences) {
    // Default key is "counter"
    // Default value is "0"
    var counter: Int by sweetPreferences.delegate(0)

    // Key is hardcoded to "usernameKey"
    // Default value is "James"
    var username: String? by sweetPreferences.delegate("James", "usernameKey") 

// Obtain a SweetPreferences instance with default SharedPreferences
val sweetPreferences = SweetPreferences.Builder().withDefaultSharedPreferences(context).build()

// Build a UserPreferences instance
val preferences = UserPreferences(sweetPreferences)

// Use the preferences in a type-safe manner
preference.username = "John Doe"
preference.counter = 34

Kotlin magic

The most important part of the library is to define properties that run code instead of just holding a value.

From the example above, when you do:

val name = preference.username

what really happening is:

val name = sweetPreferences.get("username", "James", String::class)

The username property is converted from a property name to a string, the "James" string is taken from the property definition and the String class is automatically inferred.

To write this simple library, we used constructs offered by Kotlin such as Inline Functions, Reified type parameters, Delegated Properties, Extension Functions and Function literals with receiver. If you are starting with Kotlin, I warmly encourage you to go check those. It's only a small part of what Kotlin has to offer to ease app development, but already allows you to create great APIs.

Next time you need to store preferences in your Android app, give SweetPreferences a try and share what you have built with it. We’d like to know your feedback!

Tell us what you think