How Do You Troubleshoot “groovy.lang.MissingPropertyException: No such property” when running a Groovy Program?

Problem scenario
You are running a Groovy program.  

Here is your code:
def input = System.console().readLine 'Please provide some input: '
def x = input
def boardArray = new String[2]
boardArray[0] = ""
boardArray[1] = ""
boardArray[1] = $x
println boardArray[1]

When you run it (i.e., with groovy foobar.groovy), you get this error:

"Caught: groovy.lang.MissingPropertyException: No such property: $x for class:
groovy.lang.MissingPropertyException: No such property"

What should you do?

Solution
To assign an element of an array, should have quotes around the variable and the $ symbol and the syntax " as String" should follow the closing quote mark.

def input = System.console().readLine 'Please provide some input: '
def x = input
def boardArray = new String[2]
boardArray[0] = ""
boardArray[1] = ""
boardArray[1] = "$x" as String   //This is the correct version
println boardArray[1]

Leave a comment

Your email address will not be published. Required fields are marked *