Explain how to ensure immutability when using inline classes, especially considering potential modifications of the underlying value. Provide examples and best practices.
Android interview question for Advanced practice.
Answer
Immutability with inline classes needs careful consideration. While the inline class itself can be declared as a value type, the underlying data might be mutable. This can introduce subtle issues. The best approach is to make sure the underlying type is immutable, too. For example: kotlin inline class ImmutableString(val value: String) //String is immutable inline class MutableIntWrapper(val value: Int) fun modifyMutableIntWrapper(wrapper: MutableIntWrapper): MutableIntWrapper { return MutableIntWrapper(wrapper.value + 1) //Creates a new wrapper } In the MutableIntWrapper example, modifications create a new wrapper instance maintaining immutability of the MutableIntWrapper itself, and the underlying Int is not changed directly. But for the ImmutableString, it's inherently immutable. Always prefer immutable types as underlying values for inline classes to guarantee true immutability.
Explanation
Even with an immutable inline class, the underlying type might be mutable, introducing potential issues if not handled carefully.