Skip to content

Using @StringDef in kotlin

Devrath edited this page Oct 24, 2024 · 5 revisions

About @StringDef

  • @StringDef is an annotation in Android that is part of the Android annotation processing framework.
  • It is used to enforce type safety when dealing with string constants.
  • Instead of using enum which is costly in terms of memory and performance, especially in Android @StringDef ensures only specific strings could be passed as values or used as parameters.

Why to use @StringDef

  • Type Safety: It helps you avoid mistakes where arbitrary strings might be passed where only specific values are expected.
  • Performance: Since Android has a limited memory footprint, using String constants is more efficient than enums, which come with additional overhead.
  • Compile-time Checking: It allows the compiler to catch invalid values passed to a function or variable at compile-time, preventing runtime errors.
  • Documentation: It makes the API clear about the valid values expected for a given argument, improving code readability.

Code

import androidx.annotation.StringDef

object UserStatus {
    const val ACTIVE = "active"
    const val INACTIVE = "inactive"
    const val BANNED = "banned"

    @Retention(AnnotationRetention.SOURCE)
    @StringDef(ACTIVE, INACTIVE, BANNED)
    annotation class Status
}

class UserManager {

    // Using @UserStatus.Status ensures only predefined values can be used.
    fun updateUserStatus(@UserStatus.Status status: String) {
        when (status) {
            UserStatus.ACTIVE -> {
                // Logic for active users
            }
            UserStatus.INACTIVE -> {
                // Logic for inactive users
            }
            UserStatus.BANNED -> {
                // Logic for banned users
            }
        }
    }
}

Usage

val userManager = UserManager()
userManager.modifyUserStatus(UserStatus.ACTIVE)
Clone this wiki locally