This code intends to create an inline class representing a positive integer. What is the potential issue and how can it be addressed?

Android interview question for Advanced practice.

Answer

The constructor allows negative values, violating the intention of representing a positive integer. Add a check in the constructor to enforce positivity.

Explanation

The code has a flaw: PositiveInt can be instantiated with a negative value because there's no constraint enforced in the constructor. To address this, add a check within the constructor to ensure value is positive. For example: inline class PositiveInt(val value: Int) { init { require(value = 0) { "Value must be non-negative" } } }. This throws an IllegalArgumentException if a negative value is provided, ensuring only positive integers are represented.

Related Questions