Monday, 13 September 2021

Enum valueOf() method - Winter'22

 The valueOf() enum method converts a specified string to an enum constant value.

An exception is thrown if the input string doesn’t match an enum value. In previous releases, using this method resulted in a runtime error.

ex :


public enum Season {WINTER, SPRING, SUMMER, FALL}

string currentSeasonInput = 'winter';

// With Winter'22

Season currentSeasonWithValueOf = Season.valueOf(currentSeasonInput);

System.debug('Current season (new technique): ' + currentSeasonWithValueOf); // result : Current season (new technique): WINTER

ex:

Before Winter’22, to get an Enum constant value from string, you had to iterate through all the values searching for a matching name.


    public enum Season {WINTER, SPRING, SUMMER, FALL}

      String currentSeasonInput = 'WINTER';

  

      // Before - searching the values()

        Map<String, Season> seasonsByName = new Map<String, Season>();

        for (Season enumValue : Season.values())

        {

            seasonsByName.put(enumValue.name().toUpperCase(), enumValue);

        }

        Season currentSeason = seasonsByName.get(currentSeasonInput);


        System.debug('Current season (older technique): ' + currentSeason);  // result : Current season (older technique): WINTER

No comments:

Post a Comment