Created
October 20, 2023 12:10
-
-
Save kishan-vadoliya/e0f4689f729b072296049cfd27abc211 to your computer and use it in GitHub Desktop.
Inline classes in Kotlin?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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