0

When I create a child node using an interpolated string I am unable to access that node again using dot notation. When I try to access the node in question I just get null. I can get the node if I loop through children() and hunt for it, but I shouldn't have to do that. The following code duplicates the problem:

// All works as expected when an interpolated string isn't used to create the child node
def rootNode = new Node(null, "root")
def childNode = new Node(rootNode, "child", [attr: "test"])
def childNodeCopy = rootNode.child[0]
println childNode.toString() // child[attributes={attr=test}; value=[]]
println childNodeCopy.toString() // child[attributes={attr=test}; value=[]]
println childNode.toString() == childNodeCopy.toString() // true

// But when an interpolated string is used the child node cannot be accessed from the root
rootNode = new Node(null, "root")
def childName = "child"
childNode = new Node(rootNode, "$childName", [attr: "test"])
childNodeCopy = rootNode.child[0]
println childNode.toString() // child[attributes={attr=test}; value=[]]
println childNodeCopy.toString() // null
println childNode.toString() == childNodeCopy.toString() // false
ubiquibacon
  • 10,451
  • 28
  • 109
  • 179

1 Answers1

1

Ahhhh, it's because internally, Node must be storing the node names as keys in a map actually, it just iterates through the names of the nodes, but as it's in Java, it won't find the children as string.equals( groovyString ) will never be true

And as Groovy Strings are not Strings, rootNode.child is returning null

As a workaround, you can do:

childNode = new Node(rootNode, "$childName".toString(), [attr: "test"]) 
childNodeCopy = rootNode.child[0] 
tim_yates
  • 167,322
  • 27
  • 342
  • 338
  • I thought I had this same issue somewhere: http://stackoverflow.com/a/7591157/438992 – Dave Newton Nov 12 '13 at 00:04
  • Using `toString()` or `as String` works, but it isn't very Groovy. Why don't they make `Node.java` into `Node.groovy` and modify the `get()` method to include a call to `toString()` before `.equals()`? – ubiquibacon Nov 12 '13 at 17:19