Skip to content

Instantly share code, notes, and snippets.

@kishan-vadoliya
Created October 20, 2023 12:10
Show Gist options
  • Save kishan-vadoliya/e0f4689f729b072296049cfd27abc211 to your computer and use it in GitHub Desktop.
Save kishan-vadoliya/e0f4689f729b072296049cfd27abc211 to your computer and use it in GitHub Desktop.
Inline classes in Kotlin?
// Why use inline classes? πŸ€”
// 🎯 Compile time safety
// 🎯 Less runtime overhead than a normal wrapper class as it "inlines" the data into its usages
// More info : https://kotlinlang.org/docs/reference/inline-classes.html
// Without inline classes 😞
data class Recipe(id: UUID)
data class Ingredient(id: UUID, recipeId: UUID)
val recipeId = UUID.randomUUID()
val incorrectIngredient = Ingredient(recipeId, recipeId) // compiles perfectly - but incorrect ID 😨
// With inline classes βœ…
inline class RecipeId(id: UUID)
inline class IngredientId(id: UUID)
data class Recipe(id: RecipeId)
data class Ingredient(id: IngredientId, recipeId: RecipeId)
val ingredientId = IngredientId(UUID.randomUUID())
// Can be quite easy to pass in the incorrect UUID without inline classes:
val doesntCompileIngredient = Ingredient(ingredientId, ingredientId) // wont compile! yay! 🎈
val recipeId = RecipeId(UUID.randomUUID())
val safeCompilingIngredient = Ingredient(ingredientId, recipeId) // compiles and is safer! πŸ”
// NOTE: Inline classes are still an experimental feature
// Use with caution πŸ§ͺ
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment