Fylke
Fylke

Reputation: 1836

Can I not put class declarations in a Groovy script?

I'm doing the puzzles at codingame.com and I'm doing them in Groovy. And I'm running into a confusing problem. Here is the file you get to put your program into (some not relevant code omitted):

input = new Scanner(System.in);

/**
 * Auto-generated code below aims at helping you parse
 * the standard input according to the problem statement.
 **/

lightX = input.nextInt() // the X position of the light of power
lightY = input.nextInt() // the Y position of the light of power
initialTX = input.nextInt() // Thor's starting X position
initialTY = input.nextInt() // Thor's starting Y position

fartherThanPossible = 100

class Point {
    Integer x
    Integer y
    Integer distanceFromTarget = fartherThanPossible
}

def currentPos = new Point(x: initialTX, y: initialTY)

What happens is that as soon as I try to instantiate the class, an exception is thrown on the last line in the code block above. The exception itself isn't very helpful and I assume this is because the file is run as a script?

at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:53)
at Answer.run on line 28

Am I not allowed to put a class declaration inside a Groovy script? The documentation seems to say that I can, as far as I can tell.

Upvotes: 1

Views: 127

Answers (1)

Rao
Rao

Reputation: 21349

Yes, it is valid to have class in side a script.

When your script is run the following is output :

$ groovy testthor.groovy 
7
8
8
9
Caught: groovy.lang.MissingPropertyException: No such property: fartherThanPossible for class: Point
groovy.lang.MissingPropertyException: No such property: fartherThanPossible for class: Point
    at Point.<init>(testthor.groovy)
    at testthor.run(testthor.groovy:21)

And that is because of incorrect statement in the last line of class definition.

Just change the script to below to fix the issue:

input = new Scanner(System.in)

/**
 * Auto-generated code below aims at helping you parse
 * the standard input according to the problem statement.
 **/

lightX = input.nextInt() // the X position of the light of power
lightY = input.nextInt() // the Y position of the light of power
initialTX = input.nextInt() // Thor's starting X position
initialTY = input.nextInt() // Thor's starting Y position

fartherThanPossible = 100
//Added 
@groovy.transform.ToString
class Point {
    Integer x
    Integer y
    //changed
    Integer distanceFromTarget
}

def currentPos = new Point(x: initialTX, y: initialTY, distanceFromTarget: farther
ThanPossible)
//Added
println currentPos.toString()

And output:

$ groovy testthor.groovy 
87
88
8
99
Point(8, 99, 100)

Upvotes: 1

Related Questions