Java text blocks
생성
- text block으로 생성되는 객체는 java.lang.String이다
String name = """red green blue""";
String name = """red
green
blue
""";
String name = """
red
green
blue""";
String name = """
red
green
red
""";
String name = """
String message = "Hello, world!";
System.out.println(message);
""";
공백
- text block은 부수적인 공백(incidental white space)와 필수공백(essential space)를 구분한다
부수적인 공백 알고리즘은 JEP378에 자세히 설명되어있다
가장 적은 공백줄을 기준으로 공백을 제거한다
void writeHTML() {
String html = """
········<html>
········ <body>
········ <p>Hello World.</p>
········ </body>
········</html>
········""";
}
void writeHTML() {
String html = """
········ <html>
········ <body>
········ <p>Hello World.</p>
········ </body>
········ </html>
········""";
}
String colors = """
red
green
blue""".indent(4);
후행공백(Trailing white space)
- text block에서 후행공백은 모두 제거된다.
- 후행공백을 활용하기 위한 세가지 전략은 다음과 같다
String r = """
trailing$$$
white space
""".replace('$', ' ');
String s = """
trailing |
white space|
""".replace("|\n", "\n");
String t = """
trailing\040\040\040
white space
""";
style guide
- 단일 줄이라면 text block보다는 큰따옴표 2개를 활용한 문자열리터열이 낫다
- 여는 기호, 닫는 기호와 텍스트들이 왼쪽 여백을 맞추지마라.
변수 이름이나 지정자가 추가되면 텍스트 블록을 다시 들여써야한다
String string = """
red
green
blue
""";
static String rgbNames = """
red
green
blue
""";
String string = """
red
green
blue
""";
static String rgbNames = """
red
green
blue
""";
- 닫는 기호를 개행하고 줄바꿈을 에스케이프로 개행방지 하는 것이 가독성에 낫다
String name = """
red
green
blue""";
String name = """
red
green
blue\
""";
- String formatted(Object ... args)
String output = """
Name: %s
Phone: %s
Address: %s
Salary: $%.2f
""".formatted(name, phone, address, salary);
- String stripIndent(): text block과 동일한 알고리즘으로 여백제거