A `configure` method for delegated properties



I’d like to see a configuration operator for delegated properties that is called when constructing the containing object and is provided with (the object instance and) the KProperty.


So far, the only point where a delegate can inspect the KProperty is when either of the operators are invoked, so for some executions it might not even be called once. When you pack a lot of meta information in delegates, you do not want to repeat something already present in the KProperty, but the KProperty info is only accessible when operators are called.


I run into this issue multiple times. Automatically putting the containing instance into the delegate is not really an issue, hence the parenthesis above. The problem came up when I looked into writing a command-line arguments EDSL based on a parser object’s properties, similar to github.com/jimschubert/kopper.

When I wanted to parse the arguments, I would allow Boolean flags to stand without a value (-f vs. -f true). In order to do so, I would prepare the arguments – which were passed to the object’s constructor – and fill up missing trues. For that however I needed the names, so that I can find and fill up the Boolean flags. The names in turn are only visible when one of the Boolean flags was retrieved by a delegate.


Similar to the other operators, allow for:

operator fun configure(self: Delegate, property: KProperty<*>) : Unit {

Regarding the call-time, I think the same as a call at the point of delegation is the way to go (by Delegate() would also configure). This would probably be very native to users, as the control flow does not differ from existing constructs too much.


You’re in luck, your desired feature already exists in 1.1 (but in a more general way). It is through the provideDelegate operator. While only the return type of this method has to be a delegate there is nothing stopping it from being defined on a delegate and just returning that delegate. It will be called to assign the delegate to the property in the owner object so is exactly at the right time to configure it (for example by using the property name to modify/create the delegate based on that name).


Thanks! That’s just beautiful, requesting a feature which turns out to actually come up in the next version :slight_smile:

Next time I should check if something I want to request is in coming up, I was just searching for similar requests on this board.


i’ve already used this feature in my project and it works ok. the only confusion: why it was implemented via custom operator? looks unusual to me.


Because this is how the other delegated property methods (getValue and setValue) are implemented.


Note that it actually works as inline extension operator if you want that. Penalties could be minimal (esp. with some minimal level of optimization such as dead code elimination).