简体   繁体   English

在groovy中定义类型的变量

[英]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? 我真正担心的是可以指定类型并同时使用def吗?

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. 是的,因为编译器会很高兴地编译并执行上面的代码,但是不会,因为将某些内容键入def并将其分配为显式类型确实没有任何意义。 Basically what you're saying is "this can have any type, but it must be a CallableStatement ". 基本上,您要说的是“可以有任何类型,但必须是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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM