Sobes.tech
Middle+

Have you used inline classes in your development experience?

sobes.tech AI

Answer from AI

Yes, I have used them. Inline classes (or value classes in Kotlin 1.5+) are used for:

  1. Enhancing type safety without overhead: They allow creating "wrappers" for primitive types or other classes, giving them a specific meaning, such as units of measurement, user ID, etc. During compilation, the Kotlin compiler replaces instances of inline classes with their underlying type, avoiding the creation of unnecessary objects.

Example:

// Defining an inline class
@JvmInline
value class UserId(val id: String)

fun findUser(id: UserId) {
    // Logic to find user by ID
}

fun main() {
    val userId = UserId("12345")
    findUser(userId) // Safe, expects UserId
    // findUser("12345") // Compilation error, expects UserId, got String
}
  1. More explicit coding of intentions: Clearly indicates what type of data is expected or returned, increasing code readability and maintainability.

  2. Minimizing object creation when working with primitives: They allow using methods and properties defined in the inline class without creating an instance of the class at runtime.

@JvmInline
value class Password(private val s: String) {
    val length: Int
        get() = s.length

    fun isValid(): Boolean = s.length >= 8
}

fun processPassword(password: Password) {
    if (password.isValid()) {
        // Processing valid password
    }
}

fun main() {
    val userPassword = Password("SecurePassword")
    processPassword(userPassword)
    println(userPassword.length) // Executed without creating a Password object
}

Using inline classes helps improve type safety and performance, especially when working with recurring data types with different semantic meanings.