插值和模板化
我正在尝试验证我对字符串插值和字符串模板的理解。
说这两个 Java 代码片段是模板化的示例是否正确?
public class Person {
//showing only relevant code
public String toString() {
return "Name: " + name + " salary: " + salary + " address: " + address;
}
}
public String toString() {
return String.format("name: %s salary: %d address: %s", name, salary, address);
}
这个 Groovy 代码片段是字符串插值的一个示例:
public class Person {
def name
def salary
def address
//showing only relevant parts of the code
public String toString() {
return """ name: ${name} salary: ${salary} address: ${address}"""
}
}
Java 和 Python 支持模板但不支持插值,这是正确的说法吗,但 Groovy 确实支持插值。
I am trying to verify my understanding of string interpolation and string templating.
Is it correct to say that the two Java code snippets are examples of templating?
public class Person {
//showing only relevant code
public String toString() {
return "Name: " + name + " salary: " + salary + " address: " + address;
}
}
public String toString() {
return String.format("name: %s salary: %d address: %s", name, salary, address);
}
This Groovy snippet is an example of string interpolation:
public class Person {
def name
def salary
def address
//showing only relevant parts of the code
public String toString() {
return """ name: ${name} salary: ${salary} address: ${address}"""
}
}
Would it be correct to say that Java and Python support templating but no interpolation, but Groovy does support interpolation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的前两个代码片段是格式化的示例。
你的第三个片段是插值。
Java 的字符串模板类似于插值,但更灵活、更强大、更安全。
Java 的字符串模板功能在 JEP 430 中进行了描述,并且它作为预览功能出现在 JDK 21 中。 这是一个使用示例:
Your first two code snippets are examples of formatting.
Your third snippet is interpolation.
Java's string templating is like interpolation, but more flexible, powerful, and safe.
Java's String Templates feature is described in JEP 430, and it appears in JDK 21 as a preview feature. Here is an example use: