Marc Knaup12/23/2020, 5:27 PM
as syntactic sugar for something like that:
val Foo.property = "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:
private const val _foo = "foo" val Foo.property get() = _foo
Because such a value is static, i.e. independent of the actual instance of
// 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
, you can’t use
in that context except for referring to other such static values or if the receiver is an
. I personally use such properties often in two situations: • add static values to an
• add static values to marker interfaces (e.g. for DSL)
jw12/23/2020, 5:40 PM
is equally as optimal in bytecode.
val Foo.property get() = "foo"
Marc Knaup12/23/2020, 5:41 PM
jw12/23/2020, 5:42 PM
Marc Knaup12/23/2020, 5:42 PM
Derek Peirce01/25/2021, 12:50 AM
where it didn't exist before. That goes beyond extension methods/vals, as it requires either more space for every
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 Knaup01/25/2021, 12:29 PM
types and for
types that are used as namespaces or implemented by objects.