Skip to content

Instantly share code, notes, and snippets.

@riggaroo

riggaroo/InlineClasses.kt

Last active Mar 2, 2020
Embed
What would you like to do?
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