Marc Knaup
12/23/2020, 5:27 PMval Foo.property = "foo"
as syntactic sugar for something like that:
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:
// 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)jw
12/23/2020, 5:40 PMval Foo.property get() = "foo" is equally as optimal in bytecode.Marc Knaup
12/23/2020, 5:41 PMMarc Knaup
12/23/2020, 5:41 PMjw
12/23/2020, 5:42 PMMarc Knaup
12/23/2020, 5:42 PMMarc Knaup
12/23/2020, 5:48 PMDerek Peirce
01/25/2021, 12:50 AMFoo 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?Marc Knaup
01/25/2021, 12:29 PMobject types and for interface types that are used as namespaces or implemented by objects.