微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

What is this "def" I heard of?

What is this "def" I heard of?
"def" is a replacement for a type name. In variable deFinitions it is used to indicate that you don't care
about the type. In variable deFinitions it is mandatory to either provide a type name explicitly or to use
"def" in replacement. This is needed to the make variable deFinitions detectable for the Groovy parser.
These deFinitions may occur for local variables in a script or for local variables and properties/fields in a
class.
Rule of thumb
You can think of "def" as an alias of "Object" and you will understand it in an instant.
Future Groovy may give "def" an additional meaning in terms of static and dynamic typing. But this is
post Groovy 1.0.
"def" can also replace "void" as the return type in a method definiton.

 

  1. def dynamic  =  1
  2. dynamic = "I am a String stored in a variable of dynamic type"
  3. int typed = 2
  4. typed = "I am a String stored in a variable of type int??"    // throws ClassCastException

The assignment of a string,to a variable of type int will fail. A variable typed with "def" allows this.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐