Apex嵌入条件语句拼接字符串报错,求可行实现方案
Flow转Apex:字符串拼接里嵌条件逻辑的坑
问题背景
把Flow里带IF条件的字符串公式转成Apex时,直接在字符串拼接块里写三元表达式报错存不了。想直接在拼接块里搞定这种逻辑,不想每次都先定义变量。
Flow原公式
'Introduction line of text. ' + BR() + BR() + IF({varTotal} > 1, "CS Account: " ,"Customer Account: ") + 'Name'
预期效果
- 当
varTotal > 1时,输出:Introduction line of text. CS Account: Name - 当
varTotal = 1时,输出:Introduction line of text. Customer Account: Name
踩坑的Apex代码
String textBlock= 'Introduction line of text.<br/><br/>' + totalSelected > 1 ? 'CS Account: ' : 'Customer Account: ' + 'Name<br/><br/>';
解决办法
核心问题是Apex的运算符优先级:字符串拼接+比三元运算符?:优先级高,代码会先把前面的字符串和totalSelected拼起来,再跟1比大小,完全偏离预期逻辑,所以报错。
给三元表达式整个套个括号,让条件判断先执行,再参与拼接,就能直接在块里完成逻辑:
String textBlock = 'Introduction line of text.<br/><br/>' + (totalSelected > 1 ? 'CS Account: ' : 'Customer Account: ') + 'Name<br/><br/>';
额外提示
要是有多处需要这种带条件的字符串拼接,都可以用这套括号的方式直接嵌进去,不用额外定义变量,省事高效。
内容的提问来源于stack exchange,提问作者Spots Knight
相关产品推荐
相关产品推荐

