Java 21 預覽功能:樣版字串 (String Template)
從 IntelliJ 新版的 release note 發現 Java 21 新增了一項預覽版功能:String Template,大致上就是 Python 的 f string,不過這裡面還說明如何實作自己的樣版字串。
用法大概像這樣:
String myName = "Heisenberg";
String a = StringTemplate.STR."Say my name: \{myName}";
// sentence:
// Say my name. You're Heisenberg.如有排版需要則用:
import java.util.FormatProcessor;
String[] products = {"Coco", "Meth"};
int[] prices = {1000, 2000};
String priceTable = FormatProcessor.FMT."""
Price Table
| %-8s\{products[0]} | %-8s\{products[1]} |
| %-8d\{prices[0]} | %-8d\{prices[1]} |
""";
// priceTable:
// Price Table
// | Coco | Meth |
// | 1000 | 2000 |個人認為整體來說不若 Python f string 來得便利,主要是在 STR.字串 這個用法上特別的不直覺,需要排版還得另外使用 FormatProcessor.FMT,然而論功能也尚稱充足了,總而言之仍然是相當歡迎的新特色,該功能目前還在預覽,未來變得更有人性也是能夠稍微期待的。

