Sobes.tech
Middle

What are inline classes in Kotlin?

sobes.tech AI

Answer from AI

Inline class is a special type of class in Kotlin that encapsulates the value of another type and does not create an additional container object at runtime unless used as a regular object. It helps prevent errors related to incorrect type usage while maintaining efficiency.

Main characteristics:

  • Value-based: Instances behave more like values than objects.
  • Wrapper Optimization: The compiler attempts to replace inline class instances with the underlying value, minimizing overhead.
  • Type Safety: Provides strong typing for the underlying value.

Example:

inline class Password(val value: String) // Declaration of an inline class for hiding passwords

fun login(password: Password) {
    // Using inline class to ensure type safety
    println("Logging in with password: ${password.value}")
}

fun main() {
    val myPassword = Password("secure_password_123")
    login(myPassword) // Passing an inline class
    // val notAPassword: String = myPassword // Compilation error - cannot assign directly to the base type
}

Restrictions:

  • Must have exactly one parameter in the primary constructor.
  • Cannot have initializer blocks (init).
  • Cannot have inner classes.
  • Cannot extend other classes except interfaces.

Optimization occurs when using an inline class as a function parameter type or return type, as well as when accessing its members. If an inline class instance is stored in a variable or field, it can be represented by the underlying type if possible. If the instance is used polymorphically (e.g., as Any), it will be wrapped.

What are inline classes in Kotlin? — Kotlin - sobes.tech