user140736
user140736

Reputation: 1919

defining variables with type in groovy

Is this valid ?

def CallableStatement st

try {
 ...     
 st = sqlConn.prepareCall("call....")
 ...
}

what I'm really worried about is can you specify type and also use def at the same time?

Upvotes: 1

Views: 173

Answers (1)

Dónal
Dónal

Reputation: 187529

Is this valid ?

Yes and no....

Yes, because the compiler will happily compile and execute the code above, but no, because it really doesn't make any sense to type something as def and also assign it as an explicit type. Basically what you're saying is "this can have any type, but it must be a CallableStatement". In my opinion, the definition above should generate a compiler error.

In practice this definition:

def CallableStatement st

Appears to be identical to:

CallableStatement st

As the following illustrates:

class Foo { 
  def List l;
}


new Foo().l = new ArrayList()  // this works
new Foo().l = "ddd"  // this throws a GroovyCastException

Upvotes: 3

Related Questions