Salesforce Apexリテラル when 値を使用する方法

構文
when literal {} (when ブロックに複数のカンマ区切りのリテラル句を使用可能)
各 when 値は一意である必要があります。たとえば、リテラル x は 1 つの when ブロック句でのみ使用できます。
when ブロックは 1 回のみ照合されます。
式に一致する when 値がない場合、when else ブロックが実行されます。

操作例
1.Apex のすべての型は null にすることができるため、when 値を null にできます。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
switch on i {
when 11 {
System.debug('when ブロック 11');
}
when null {
System.debug('null 値');
}
when else {
System.debug('test ' + i);
}
}
switch on i { when 11 { System.debug('when ブロック 11'); } when null { System.debug('null 値'); } when else { System.debug('test ' + i); } }
switch on i {
   when 11 {
       System.debug('when ブロック 11');
   }
   when null {
       System.debug('null 値');
   }
   when else {
       System.debug('test ' + i);
   }
}

2.単一値の例
when 値に整数リテラルを使用します。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
switch on i {
when 11 {
System.debug('when ブロック 2');
}
when -6 {
System.debug('when ブロック -6');
}
when else {
System.debug('arkt');
}
}
switch on i { when 11 { System.debug('when ブロック 2'); } when -6 { System.debug('when ブロック -6'); } when else { System.debug('arkt'); } }
switch on i {
   when 11 {
       System.debug('when ブロック 2');
   }
   when -6 {
       System.debug('when ブロック -6');
   }
   when else {
       System.debug('arkt');
   }
}

3.複数値の例
Apex switch ステートメントはフォールスルーしませんが、when 句に照合する複数のリテラル値を含めることができます。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
switch on i {
when 22, 33, 44 {
System.debug('when block 22 and 33 and 44');
}
when else {
System.debug('ottt');
}
}
switch on i { when 22, 33, 44 { System.debug('when block 22 and 33 and 44'); } when else { System.debug('ottt'); } }
switch on i {
   when 22, 33, 44 {
       System.debug('when block 22 and 33 and 44');
   }
   when else {
       System.debug('ottt');
   }
}

 

Salesforce

Posted by arkgame