现在的位置: 首页 > 综合 > 正文

What is this “def” I heard of?

2013年11月19日 ⁄ 综合 ⁄ 共 893字 ⁄ 字号 评论关闭

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.

抱歉!评论已关闭.