Kotlin Tip #34: Prefer Inline Classes for Wrapping Primitive Types — 100 Kotlin Tips in 100 Days

Raphael De Lio
Kotlin with Raphael De Lio
2 min readMar 14, 2024

--

Twitter | LinkedIn | YouTube | Instagram
Tip #33: Using By Lazy For Efficient Property Initialization

An inline class in Kotlin is defined using the inline keyword before the class declaration. Its primary purpose is to wrap another type. At runtime, instances of an inline class are represented using the value of the type they are wrapping, which means the wrapping comes at no additional memory cost.

Here’s a simple illustration:

inline class Password(val value: String)

The Password inline class wraps a String, but at runtime, it's merely a String—no extra object overhead. Yet, in your code, you treat it as a distinct type, which can significantly enhance readability and maintainability.

Inline classes in Kotlin offer several advantages, such as improving type safety, making code more readable, and maintaining efficiency. They help prevent confusion between different types of data that use the same underlying type, like strings or integers, by giving them specific names (e.g., Password or UserId) in your code. This makes it easier to understand what kind of data a function expects. Additionally, because inline classes are replaced by their actual value at runtime, they don’t make your application use more memory, ensuring your application stays efficient.

I hope you have enjoyed this tip of our series! Don’t forget to subscribe and stay tuned for more Kotlin tips!

Stay curious!

Tip #35: Use Tailrec for Efficient Recursion

Contribute

Writing takes time and effort. I love writing and sharing knowledge, but I also have bills to pay. If you like my work, please, consider donating through Buy Me a Coffee: https://www.buymeacoffee.com/RaphaelDeLio

Or by sending me BitCoin: 1HjG7pmghg3Z8RATH4aiUWr156BGafJ6Zw

Follow Me on Social Media

Stay connected and dive deeper into the world of Kotlin with me! Follow my journey across all major social platforms for exclusive content, tips, and discussions.

Twitter | LinkedIn | YouTube | Instagram

--

--