Mobile Development Kotlin Subjective
Oct 04, 2025

What are inline classes (value classes) and their benefits?

Detailed Explanation
Value classes (formerly inline classes) provide type safety without runtime overhead:\n\n1. Declaration\n• Wrap primitive types for type safety\n• No runtime object creation\n• Example:\n\n@JvmInline\nvalue class UserId(val value: Int)\n\n@JvmInline\nvalue class Email(val value: String)\n\n\n2. Type Safety Benefits\n\nfun createUser(id: UserId, email: Email) {\n // Implementation\n}\n\n// Compile-time safety\nval userId = UserId(123)\nval email = Email("user@example.com")\n\ncreateUser(userId, email) // OK\n// createUser(email, userId) // Compilation error\n\n\n3. No Runtime Overhead\n\n// At runtime, this:\nval userId = UserId(123)\nval id = userId.value\n\n// Becomes this (no wrapper object):\nval id = 123\n\n\n4. Methods and Properties\n\n@JvmInline\nvalue class Distance(val meters: Double) {\n val kilometers: Double get() = meters / 1000\n val miles: Double get() = meters * 0.000621371\n \n operator fun plus(other: Distance) = Distance(meters + other.meters)\n operator fun compareTo(other: Distance) = meters.compareTo(other.meters)\n}\n\nval d1 = Distance(1000.0)\nval d2 = Distance(500.0)\nval total = d1 + d2\nprintln(total.kilometers) // 1.5\n\n\n5. Interface Implementation\n\ninterface Printable {\n fun print()\n}\n\n@JvmInline\nvalue class Name(val value: String) : Printable {\n override fun print() {\n println("Name: $value")\n }\n}\n\n\n6. Restrictions\n• Must have exactly one property in primary constructor\n• Property must be val\n• Cannot have init blocks\n• Cannot have backing fields\n• Cannot extend classes (can implement interfaces)\n\n7. Use Cases\n• Type-safe APIs (IDs, measurements)\n• Domain modeling without performance cost\n• Preventing parameter mix-ups\n• Adding behavior to primitive types
Discussion (0)

No comments yet. Be the first to share your thoughts!

Share Your Thoughts
Feedback