hon*_*ute 4 java object destructuring
在javascript中,存在对象解构,因此,如果中间对象被重用多次,我们可以分解对象并仅使用end键。例如)
const person = {
firstName: "Bob",
lastName: "Marley",
city: "Space"
}
Run Code Online (Sandbox Code Playgroud)
因此,person.<>与其调用获取每个值,不如将其分解
console.log(person.firstName)
console.log(person.lastName)
console.log(person.city)
Run Code Online (Sandbox Code Playgroud)
变形:
const { firstName, lastName, city } = person;
Run Code Online (Sandbox Code Playgroud)
并这样调用:
console.log(firstName)
console.log(lastName)
console.log(city)
Run Code Online (Sandbox Code Playgroud)
Java中有类似的东西吗?我有这个Java对象,我需要从中获取值,并且必须像这样调用长的中间对象名称:
myOuterObject.getIntermediateObject().getThisSuperImportantGetter()
myOuterObject.getIntermediateObject().getThisSecondImportantGetter()
...
Run Code Online (Sandbox Code Playgroud)
我想这个解构它在某种程度上,只是调用的最后一个方法getThisSuperImportantGetter(),getThisSecondImportantGetter()更清洁的代码。
Ste*_*erl 15
Java 语言架构师Brian Goetz最近谈到了在即将推出的 Java 版本中添加解构的问题。在他的论文中寻找侧边栏:模式匹配章节:
我非常不喜欢当前的语法建议,但根据 Brian 的说法,您的用例将如下所示(请注意,此时这只是一个建议,不适用于任何当前版本的 Java):
public class Person {
private final String firstName, lastName, city;
// Constructor
public Person(String firstName, String lastName, String city) {
this.firstName = firstName;
this.lastName = lastName;
this.city = city;
}
// Deconstruction pattern
public pattern Person(String firstName, String lastName, String city) {
firstName = this.firstName;
lastName = this.lastName;
city = this.city;
}
}
Run Code Online (Sandbox Code Playgroud)
您应该能够在 instanceof 检查中使用该解构模式,例如:
if (o instanceof Person(var firstName, lastName, city)) {
System.out.println(firstName);
System.out.println(lastName);
System.out.println(city);
}
Run Code Online (Sandbox Code Playgroud)
抱歉,Brian 在他的例子中没有提到任何直接的解构赋值,我不确定是否以及如何支持这些。
附带说明:我确实看到了与构造函数的预期相似性,但我个人不太喜欢当前的提议,因为“解构函数”的参数感觉像是外参数(Brian 在他的论文中说了这么多)。对我来说,在每个人都在谈论不变性和使方法参数化的世界中,这相当违反直觉final。
我更愿意看到 Java 跳过围栏并支持多值返回类型。类似的东西:
public (String firstName, String lastName, String city) deconstruct() {
return (this.firstName, this.lastName, this.city);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
913 次 |
| 最近记录: |