Java object destructuring

lion_bash picture lion_bash · Jun 13, 2019 · Viewed 9.9k times · Source

In javascript there is object destructuring so we can break down objects and just use the end key if the intermidiate objects are resused multiple times. e.g)

const person = {
  firstName: "Bob",
  lastName: "Marley",
  city: "Space"
}

So instead of calling person.<> to get each value we can destructure it like this

console.log(person.firstName) 
console.log(person.lastName) 
console.log(person.city) 

Destructured:

const { firstName, lastName, city } = person;

And call like this:

console.log(firstName)
console.log(lastName)
console.log(city)

Is there something similar in Java? I have this Java Object that I need to get the value from and have to call long intermediate object names like this:

myOuterObject.getIntermediateObject().getThisSuperImportantGetter()
myOuterObject.getIntermediateObject().getThisSecondImportantGetter()
...

I would like this destructure it somehow and just call the last method getThisSuperImportantGetter(), getThisSecondImportantGetter() for cleaner code.

Answer

Sero picture Sero · Jun 13, 2019

As far as i know, java doesn't support this.

Other JVM language called Kotlin does support this

Kotlin | Destructuring Declarations