Lazy
The Lazy
aspect can be used to make a property be initialized lazily, i.e. on first access. This is the equivalent to the Oxygene or Swift lazy
keywords.
Lazy
can only be applied to properties with an initializer value. When present, rather than being called initialized on object construction, the property will not initialize until it is accessed the first time (and the initializer will never run if the property is never accessed at runtime).
Because Lazy
generates an implicit getter method for the property that runs the initializer on first call, there is a minor access overhead to access a lazy property (in exchange for saved time on object creation).
[Lazy]
property Length: Integer := SlowOperation();
[Lazy]
public int Length { get; } = SlowOperation();
@Lazy var Length: Int32 = SlowOperation()
@Lazy public int Length { __get; __set; } = SlowOperation();
<Lazy> Public Property Length As Int32 = SlowOperation()
Oxygene, Swift and Mercury also provide a native keyword for lazy properties:
property Length: Integer := SlowOperation(); lazy; // Oxygene native syntax
lazy var Length2: Int32 = SlowOperation() // Swift native syntax
Public Lazy Property Length2 As Int32 = SlowOperation() ' Mercury native syntax
See Also
- Lazy Properties in Oxygene
- Lazy Properties in Mercury