Skip to content

Instantly share code, notes, and snippets.

@riggaroo
Last active March 2, 2020 06:04
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save riggaroo/3e0fd1cad1c3da76c4285677fe148015 to your computer and use it in GitHub Desktop.
Save riggaroo/3e0fd1cad1c3da76c4285677fe148015 to your computer and use it in GitHub Desktop.
Have you heard about 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