Nested object initializers
You can use object initializers to create and initialize properties on nested objects within new statements. If an object property in a property initializer expression is itself an object, the value you assign can be a new object with its own object initializer.
For example, suppose you have the following code:
var testSet = new TestSet() // Create a test set.
testSet.name = "Root" // Set the name of the test set.
var test = new Test() // Create and initialize a test.
test.name = "test1"
testSet.tests.add(test) // Add the new test to the array of the test set.
testSet.tests.add(new Test()) // Create another test and add it to the array.
testSet.tests.get(1).final = true // Set the final property on the second test in the array.
testSet.tests.get(1).type = new TestType() // Create a test type and assign the type property
// on the second test in the array to that type.
var testStyle = new TestStyle() // Create and initialize a test style.
testStyle.color = Red; // Gosu infers which enum class is appropriate.
testStyle.number = 5
testSet.style = testStyle // Set the style property of the test set.
return testSet.toXML() // Convert the test set to XML.
You can rewrite the preceding code by using nested new object expressions with their own object initializers to reflect visually the nested object structure that the code creates.
var testSet = new TestSet() { // Create a test set.
:name = "Root", // Set the name of the test set.
:tests = {
new Test() {:name = "test1"}, // Create and initialize a test and add it to the array.
new Test() { // Create another test and add it to the array
:final = true, // Set the final property to true on the second test.
:type = new TestType() // Create a test type and set the type property
} // on the second test in the array to that type.
},
:style =
new TestStyle() { // Create and initalize a test style and set the
:color = Red, // style of the test set to that style.
:number = 5
}
}
Nested object initializers are especially useful when constructing in-memory XML data structures.
