`
touchmm
  • 浏览: 1037200 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

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. defdynamic=1
  2. dynamic="IamaStringstoredinavariableofdynamictype"
  3. inttyped=2
  4. typed="IamaStringstoredinavariableoftypeint??"//throwsClassCastException

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

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics