Last updated
Last updated
When working with the mx-sdk-as
and defining VM-compatible enums, the @enumType
annotation is crucial. It allows the SDK to handle the conversion of enums into a form that's compatible with the VM, adhering to specific constraints. Here’s an elaboration on the provided details and how they impact the use of enums within this context:
To declare an enum that is compatible with the VM, you must prefix it with the @enumType
annotation. This is necessary because it signals the SDK to generate the required boilerplate code, ensuring the enum works correctly with the VM's memory management and type system. For instance:
This definition informs the SDK that MyEnum
is not just a regular enum but one that should be treated specially for VM compatibility.
When you assign specific values to the enum cases, like setting FirstCase = 5
or SecondCase = 10
, these assignments are ignored. This behavior is crucial to understand because it deviates from standard TypeScript, where these values can carry significance. In this context, the enum values are more about distinct identifiers rather than their assigned numeric values:
Even though you assign 5
and 10
, these values are not used by the SDK-generated code, which treats the enum purely as distinct identifiers.
The transformation of enums into classes at compile-time is a significant alteration. This change is driven by the need to manage heap allocations efficiently. The SDK generates a class structure where each enum value becomes a static method that returns an instance of the class representing the enum case. This design allows for more sophisticated handling and integration with the VM's memory management mechanisms:
This class structure is the underlying implementation that the SDK generates, even though you define them as enums. It ensures that the enums can be utilized efficiently and effectively within the VM environment.
Given that enums are internally transformed into classes, using them with switch statements requires caution. The comparison in switch cases might not behave as expected if the enum values are not simple integers but instances of a class. You might need to adjust your logic or the way you handle these enums in switch statements, ensuring that the comparisons are appropriate for the class instances rather than expecting primitive integer values.