Sweet.apex

  • Docs
  • Tutorials
Docs Menu
  • Sweet.apex Core
    • Transpilation
    • Grammar
    • Command
    • Config
  • Features
    • Action
    • Apex Doc
    • Array Creation
    • Aspect
    • Cast
    • Default Value
    • Enum
    • File
    • Function
    • Identity
    • Injection
    • Lambda
    • Log
    • Mod
    • Not Null
    • Operator
    • Optional
    • Reflection
    • Rethrow
    • Switch
    • Template String
    • Template
    • Script
    • Tagged String
    • Annotation
    • Nullable
    • Var
    • Val
    • Map Access
    • Constructor
    • Transaction
    • Destructure
    • Import Static
    • Pipeline
    • Varargs
    • Patch
    • Import As
  • Plugin Development
    • Feature
    • Test Case

Destructure Guide

Destructure

Feature Overview

This feature enables destructuring from list/map/sobject.

Prerequisite

None

Sweet Apex Example

public class DestructureDemo {
    public static void main() {
        List names = new List{ 'Wilson', 'Adam' };
        String { p1, p2 } = names;

        Map infos = new Map{ 'a' => 1, 'b' => '2' };
        { a: Integer count, b: String id } = infos;

        Account ac = new Account(Name='test acc');
        { Name: String name } = ac;

        List numbers = new List{ 1, 2, 3, 4, 5 };
        Integer { first, _ } = numbers;
        Integer { _, last } = numbers;

        List signs = new List{};
        String { sign : String = 'stop' } = signs;
    }
}

Transpiled Apex

public class DestructureDemo {
    public static void main() {
        List names = new List{ 'Wilson', 'Adam' };
        List destructure_1 = (List)names;
        String p1 = (String)destructure_1.get(0);
        String p2 = (String)destructure_1.get(1);

        Map infos = new Map{ 'a' => 1, 'b' => '2' };
        Map destructure_6 = (Map)infos;
        Integer count = (Integer)destructure_6.get('a');
        String id = (String)destructure_6.get('b');

        Account ac = new Account(Name = 'test acc');
        SObject destructure_11 = (SObject)ac;
        String name = (String)destructure_11.get('Name');

        List numbers = new List{ 1, 2, 3, 4, 5 };
        List destructure_15 = (List)numbers;
        Integer first = (Integer)destructure_15.get(0);
        List destructure_17 = (List)numbers;
        Integer last = (Integer)destructure_17.get(destructure_17.size() - 1);

        List signs = new List{  };
        List destructure_21 = (List)signs;
        String sign = (String)Sweet.defaultIfNull(destructure_21.get(0), 'stop');
    }
}

Usage

Destructuring is built on the base of type inference. Should the type inference go wrong, the generated destructuring code might fail.

You can insert one _ as a placeholder when destructuring a list.

Also you can append default values during destructuring.

Contribute on Github! Edit this section.