Kotlin Enums Tutorial for Android: Getting Started

In this tutorial, you’ll build an Android app, using the full potential of Kotlin Enums to handle a list of cartoon avatars and help your users easily create their profiles. By Caio Fukelmann Landau.

Leave a rating/review
Download materials
Save for later
Share

Kotlin enums are a crucial part of the language. They are, in their most basic form, collections of predefined constant elements. Now that’s a mouthful!

In this tutorial, you’ll learn what that means, plus what enums are capable of in Kotlin. You’ll build an the app that uses enums to create a cartoon avatar selection feature, and learn about:

  • What enums are — and aren’t — useful for
  • How to use when() for flow control with enums
  • A way to add extra functionality to enums
  • How to reference an enum constant using its name
  • An overview of best practices and gotchas to look out for

Ready to learn more? Then read on!

Getting Started

Download the starter project by clicking the Download Materials button at the top or bottom of the tutorial.

Open your project on Android Studio 4.1 or higher. Select Open an Existing Project and point it to the starter project you just extracted:

Instruction for opening a project on Android Studio

The starter project has a few files you should get acquainted with:

  • MainActivity.kt: Your app’s main user interface, which is what you see when you run the project
  • CartoonAvatarAdapter.kt: This file contains a ListAdapter. MainActivity uses this adapter to populate the RecyclerView containing all the avatar options below the “Pick an avatar” TextView (which is empty for now).
  • AvatarSelectedActivity.kt: You’ll use this activity to display the user’s selection. For now, there’s nothing starting it.
  • Utils.kt: This contains a small extension method that returns the first letter of a string and capitalizes it. You’ll use this method in AvatarSelectedActivity to display the user’s initial.
Note: For more details about RecyclerView, read our Android RecyclerView Tutorial.

Additionally, some strings you’ll use in this tutorial are already conveniently included for you. Find them in res/values/strings.xml.

Build and run the project. You’ll see a screen that says “Enter your details to continue”:

Starter project with text that says "Enter your details to continue"

This app doesn’t do anything yet. Next, you’ll make it come to life — and learn about Kotlin enums in the process! But first, an introduction to enums.

Kotlin Enums

In short, Kotlin enums are a way to describe a set of predefined constants in your code. But what does this mean, exactly?

When you’re modeling your app’s data, some concepts will have a limited set of possibilities. An example is an app that supports light and dark modes. In a case like this, you define an enum with two predefined cases: LIGHT and DARK. No other cases are possible — those are the only possible modes.

When you have a well-defined realm of possibilities, enums are a great candidate. By using them, your code has compile-time checks that prevent the developer from using an undefined case. You can’t reference an app mode called COLORFUL when the only options are LIGHT and DARK. That same characteristic makes enums unsuitable for variable or dynamic sets of data. You can’t define enum cases at runtime, and there’s no reason to: It would defeat their purpose of holding a predefined set of values. It’s also better for performance, as you won’t have to compare String values, for instance.

Are Enums Bad for Memory Management?

The question of whether enums are bad for memory management emerged a long time ago, way before Google announced that Kotlin was its preferred language for Android app developers. The short answer is: not anymore. Enums are fine now. There are two improvements that contributed to this:

  • Dalvik vs ART: Before Lollipop, Android used a runtime called Dalvik. Engineers designed this runtime for a different reality than today: Devices had minimal resources back then. Since enums are constant values, they’re always using their necessary memory, and memory allocations then were very expensive. Fast-forward to Lollipop, and the default runtime changed to Android Runtime, or ART. This is a vast improvement for modern devices, and the concerns around enums are no longer relevant. You can find more information about this in the Android Runtime (ART) and Dalvik article from Android’s documentation.
  • R8: Another concern about enums was the app size overhead, as they use significantly more space than integer constants. Without diving too deep into this, R8 is a compiler that cleans and optimizes your code when building your app. It replaces ProGuard. Among its many other features, R8 helps remove the overhead from enums whenever possible by understanding how your code uses them. The Android documentation has more details about this in the Shrink, obfuscate, and optimize your app guide.

Now that you know enums are good, it’s time to define them.

Defining a Basic Enum

In Android Studio, open CartoonAvatarAdapter.kt. Inside the adapter class, you’ll see a data class called Item. Notice how it contains imageResource, which is an Android resource ID for the avatar image. You’ll change that now to instead use an enum.

In the project navigation:

.

  1. Right-click your main package, com.raywenderlich.android.cartoonsocialclub, and select New > Kotlin File/Class
  2. .

  3. In the pop-up, name your file CartoonAvatar, select Enum class and press enter.

Instructions for creating a CartoonAvatar enum on Android Studio

Inside the newly created CartoonAvatar.kt add the following code:

enum class CartoonAvatar {
  DOG,
  MONSTER,
  OCTOPUS,
  NONE
}

Now, you’ve got your enum for the different types of avatars that the app will support. Congratulations on creating your first enum!

Using The Enum

Now that you have an enum with all possible avatar selections, it’s time to use it with your code. Go back to CartoonAvatarAdapter.kt, find // TODO 1 and replace Item with the following:

data class Item(
  // 1
  val avatar: CartoonAvatar,
  var isSelected: Boolean
) {
  // 2
  @DrawableRes
  var imageResource = when (avatar) {
    CartoonAvatar.DOG -> R.mipmap.avatar_dog
    CartoonAvatar.MONSTER -> R.mipmap.avatar_monster
    CartoonAvatar.OCTOPUS -> R.mipmap.avatar_octopus
    CartoonAvatar.NONE -> R.mipmap.avatar_none
  }
}

Here’s what the code above does:

  1. Instead of receiving the Android drawable resource directly, Item now receives an instance of your new enum, CartoonAvatar. In doing so, you’ll ensure that an item can only be one of the possible cartoon avatars.
  2. Now, imageResource is a computed property. Using when(), your logic defines which image resource to use based on the CartoonAvatar passed. Now the user of Item doesn’t need to know about Android image resources.