Kotlin enforce value of property being set by a specific class

Viewed 65

Is it possible to enforce the value of a property to be obtained only by another class?

I have val itemValue by ItemValueDelegator() and ItemValueDelegator returns an enum (ItemValue) after some business rule logic.

can I enforce somehow that the value of itemValue is always obtained from ItemValueDelegator?

I want to make impossible to do: val itemValue = ItemValue.STOCK

1 Answers

val modifier already makes it impossible to assign new value to it. Calls on itemValue will only call getValue() function in the ItemValueDelegator. What you can do is hide the enums within the class of the delegate and make the itemValue hold the ordinal.

Edit:

You need to perform runtime validation. In the init block should check if the itemVal is provided by a delegate. That involves using kotlin-reflect and checking that underlying KProperty delegate is of type ItemValueDelegator or null, if isn't, just throw error("itemValue should be provided by ItemValueDelegator")

Related