Java object destructuring
Java Language Architect Brian Goetz has recently talked about adding destructuring to an upcoming version of Java. Look for the Sidebar: pattern matching chapter in his paper:
Towards Better Serialization
I strongly dislike the current proposal of the syntax, but according to Brian your use case will look like the following (please note, that at this point this is a proposal only and will not work with any current version of 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;
}
}
You should than be able to use that deconstruction pattern for instance in an instanceof check like so:
if (o instanceof Person(var firstName, lastName, city)) {
System.out.println(firstName);
System.out.println(lastName);
System.out.println(city);
}
Sorry, Brian does not mention any direct destructuring assignment in his examples, and I'm not sure if and how these will be supported.
On a side note: I do see the intended similarity to the constructor, but I personally do not like the current proposal that much, because the arguments of the "deconstructor" feel like out-parameters (Brian says as much in his paper). For me this is rather counter-intuitiv in a world where everybody is talking about immutability and making your method parameters final
.
I would rather like to see Java jump over the fence and support multi-value return types instead. Something along the lines of:
public (String firstName, String lastName, String city) deconstruct() {
return (this.firstName, this.lastName, this.city);
}
As far as i know, java doesn't support this.
Other JVM language called Kotlin does support this
Kotlin | Destructuring Declarations