Apex sObject Switchのサンプル

概要
sObject 値で切り替える場合、instanceof チェックとキャストを暗黙的に実行できます。
たとえば、if-else ステートメントを使用する次のコードがあるとします。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
if (sobject instanceof Account) {
Account acc = (Account)sobject;
System.debug('account' + acc);
} else if (sobject instanceof Contact) {
Contact cc = (Contact)sobject;
System.debug("contact" +cc);
} else {
System.debug('default aa');
}
if (sobject instanceof Account) { Account acc = (Account)sobject; System.debug('account' + acc); } else if (sobject instanceof Contact) { Contact cc = (Contact)sobject; System.debug("contact" +cc); } else { System.debug('default aa'); }
if (sobject instanceof Account) {
   Account acc = (Account)sobject;
   System.debug('account' + acc);
} else if (sobject instanceof Contact) {
   Contact cc = (Contact)sobject;
   System.debug("contact" +cc);
} else {
   System.debug('default aa');
}

このコードを次の switch ステートメントで置き換えて簡略化できます。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
switch on sobject {
when Account acc {
System.debug('account ' + acc);
}
when Contact cc {
System.debug('contact ' + cc);
}
when null {
System.debug('null');
}
when else {
System.debug('default');
}
}
switch on sobject { when Account acc { System.debug('account ' + acc); } when Contact cc { System.debug('contact ' + cc); } when null { System.debug('null'); } when else { System.debug('default'); } }
switch on sobject {
   when Account acc {
       System.debug('account ' + acc);
   }
   when Contact cc {
       System.debug('contact ' + cc);
   }
   when null {
       System.debug('null');
   }
   when else {
       System.debug('default');
   }
}

 

IT

Posted by arkgame