What is wrong with the following code snippet that uses an inline class, and how can you fix it to ensure immutability?

Android interview question for Advanced practice.

Answer

The var keyword allows modification of the Name object, violating immutability. It should be a val.

Explanation

The issue is that the Name object is declared using var, making it mutable. Even though the inline class itself is supposed to represent a value (and its underlying value is immutable), the var keyword allows reassigning the name variable to a different Name object. To enforce immutability, change the declaration of name from var to val, preventing reassignment.

Related Questions