https://kotlinlang.org logo
m

Marc Knaup

12/23/2020, 5:27 PM
It would be great to have this:
Copy code
val Foo.property = "foo"
as syntactic sugar for something like that:
Copy code
private const val _foo = "foo"
val Foo.property get() = _foo
Typically such a construct is used when the value • is computed and must not change between invocations • is expensive to compute even if pure For example:
Copy code
// avoid that value changes
val Foo.staticProperty = generateRandomId()

 // avoid repeated expensive computation
val Foo.expensiveProperty = someExpensiveSetup()

 // avoid temporary object creation
val Foo.someComplexData = SomeComplexData(…)
val Foo.someDependentProp1 get() = someComplexData.prop1
val Foo.someDependentProp2 get() = someComplexData.prop2
val Foo.someDependentProp3 get() = someComplexData.prop3
val Foo.someDependentProp4 get() = someComplexData.prop4
Because such a value is static, i.e. independent of the actual instance of
Foo
, you can’t use
this
in that context except for referring to other such static values or if the receiver is an
object
. I personally use such properties often in two situations: • add static values to an
object
or
companion object
• add static values to marker interfaces (e.g. for DSL)
1
j

jw

12/23/2020, 5:40 PM
You don't really need a named const there. It just wastes a symbol.
val Foo.property get() = "foo"
is equally as optimal in bytecode.
m

Marc Knaup

12/23/2020, 5:41 PM
That only works for very simple cases. If you add plenty of getters that also depend on each other, you create a huge amount of temporary objects.
Same if the object creation is expensive.
j

jw

12/23/2020, 5:42 PM
Your initial proposal indicated nothing about such cases. I thought you just wanted an optimization for constant expressions.
m

Marc Knaup

12/23/2020, 5:42 PM
Yeah, my focus is on having only a single initialization. I’ll add a better example for that, thanks.
Done
d

Derek Peirce

01/25/2021, 12:50 AM
Now it looks like you're trying to store a new field-backed property in
Foo
where it didn't exist before. That goes beyond extension methods/vals, as it requires either more space for every
Foo
allocation across the entire program, or a synchronized global map of `Foo`s to their new properties. This would not be the syntactic sugar you're looking for. As the examples no longer require constants, why not just declare the property directly?
m

Marc Knaup

01/25/2021, 12:29 PM
In my example all of them are constants, allocated once per class, not per instance. This is mostly useful for
object
types and for
interface
types that are used as namespaces or implemented by objects.