21 Mayıs 2023 Pazar

JEP 430 - String Interpolation veya String Templates - JDK 21 İle Geliyor

Giriş
Açıklaması şöyle
Java provides three predefined templates for this purpose RAW, STR and FMT. 
1. STR string interpolation yapar
2. FMT string interpolation ve custom formatting yapar 

1. STR
Açıklaması şöyle
The new way to work with Strings in Java is called template expression, a programmable way of safely interpolating expressions in String literals. And even better than just interpolating, we can turn structured text into any object, not just a String.

The create a template expression, we need two things:

1. A template processor
2. A template containing wrapped expressions like \{name}
Açıklaması şöyle. Formatlamak istenilen değişken string içinde \{variable_name} şeklinde kullanılır
The prefix STR is the string template provided by Java for the string composition and interpolation. 
Örnek
Şöyle yaparız
String name = "Joan";

String info = STR."My name is \{name}";
assert info.equals("My name is Joan");   // true
Örnek - Invoke Methods
Şöyle yaparız
var name = "Ben";
var tempC = 28;

var greeting = STR."Hello \{this.user.firstname()}, how are you?\nIt's \{tempC}°C today!";
Örnek - Invoke Methods and Access Fields
Şöyle yaparız
String s = STR."You have a \{getOfferType()} waiting for you!";
// s: "You have a gift waiting for you!"
String t = STR."Access at \{req.date} \{req.time} from \{req.ipAddress}";
// t: "Access at 2022-03-25 15:34 from 8.8.8.8"
Örnek - Arithmetic Operations
Şöyle yaparız
int x = 10, y = 20;
String s = STR."\{x} + \{y} = \{x + y}";
// s: "10 + 20 = 30"
Örnek - Evaluation Order
Şöyle yaparız
int index = 0;
String data = STR."\{index++}, \{index++}, \{index++}, \{index++}";
// data: "0, 1, 2, 3"

Örnek - Double Quotes
Şöyle yaparız
String filePath = "tmp.dat";
File file = new File(filePath);
String msg = STR."The file \{filePath} \{file.exists() ? "does" : "does not"} exist";

Multi-Line Templates and Expressions
Java text blocks kullanılabilir
Örnek - Invoke Methods
Şöyle yaparız
String time = STR."The time is \{
    // The java.time.format package is very useful
    DateTimeFormatter
      .ofPattern("HH:mm:ss")
      .format(LocalTime.now())
} right now";
// time: "The time is 12:34:56 right now"
Örnek - HTML
Şöyle yaparız
String title = "My Web Page";
String text  = "Hello, world";
String html = STR."""
        <html>
          <head>
            <title>\{title}</title>
          </head>
          <body>
            <p>\{text}</p>
          </body>
        </html>
        """;
| """
| <html>
|   <head>
|     <title>My Web Page</title>
|   </head>
|   <body>
|     <p>Hello, world</p>
|   </body>
| </html>
| """
Örnek - JSON
Şöyle yaparız
String name    = "Joan Smith";
String phone   = "555-123-4567";
String address = "1 Maple Drive, Anytown";
String json = STR."""
    {
        "name":    "\{name}",
        "phone":   "\{phone}",
        "address": "\{address}"
    }
    """;
| """
| {
|     "name":    "Joan Smith",
|     "phone":   "555-123-4567",
|     "address": "1 Maple Drive, Anytown"
| }
| """
Örnek
Şöyle yaparız. Expression değişkenleri de çoklu satır şeklinde kullanılabiliyor.
var json = STR."""
{
    "user": "\{this.user.firstname()}",
    "temperatureCelsius: \{tempC}
}
""";

// Not only the template itself can be multi-line, expressions can be too, 
// including comments!
var json = STR."""
{
  "user": "\{
    // We only want to use the firstname
    this.user.firstname()
  }",
  "temperatureCelsius: \{tempC}
}
""";

2. FMT
Açıklaması şöyle. Formatlamak istenilen değişken string içinde %formatter\{variable_name} şeklinde kullanılır
FMT is another processor which is like the STR but also interprets the formats specified in expression
Örnek
Şöyle yaparız
String formatted = FMT."The price is: \{price, number, currency}";
// formatted: "The price is: $50.00"

Örnek - %12s
Şöyle yaparız
rrecord Rectangle(String name, double width, double height) {
  double area() {
    return width * height;
  
}
Rectangle[] zone = new Rectangle[] {
  new Rectangle("Alfa", 17.8, 31.4),
  new Rectangle("Bravo", 9.6, 12.4),
  new Rectangle("Charlie", 7.1, 11.23),
};
String table = FMT."""
    Description     Width    Height     Area
    %-12s\{zone[0].name}  %7.2f\{zone[0].width}  %7.2f\{zone[0].height}     %7.2f\{zone[0].area()}
    %-12s\{zone[1].name}  %7.2f\{zone[1].width}  %7.2f\{zone[1].height}     %7.2f\{zone[1].area()}
    %-12s\{zone[2].name}  %7.2f\{zone[2].width}  %7.2f\{zone[2].height}     %7.2f\{zone[2].area()}
    \{" ".repeat(28)} Total %7.2f\{zone[0].area() + zone[1].area() + zone[2].area()}
    """;
| """
| Description     Width    Height     Area
| Alfa            17.80    31.40      558.92
| Bravo            9.60    12.40      119.04
| Charlie          7.10    11.23       79.73
|                              Total  757.69
| """
3. RAW
Örnek ver



Hiç yorum yok:

Yorum Gönder