def
- Purpose
- The word
defis used to define a "method" , "property" or "variable". The definition of methods and variables can occur almost anywhere in the body of a program. The properties are declared in the main body of a class.- A property is, by default, a publicly accessible and modifiable value that is owned by a class
- The language has many predefined methods. For example, the method
Math.sqrt()enables it to calculate the square root of a number. Often though, it is useful to be able to define your own methods, as their use greatly enhances the readability and reliability of programs.- Also methods may have parameters passed to them. For example
"g" is called a "formal parameter" for the methoddef vat(g) {1.175 * g}vat(). It tells the computer that one number is going to be "passed" to the method when the method is used - and inside the method we have decided to use the letter g to represent the variable.- The method is "called" or used like this - for example
and in this case "p" is the "actual parameter" for the methodprint "VAT inclusive price " print vat(p)vat(). Whatever value "p" has will be used inside the method wherever reference is made to the "formal parameter" - Examples
@Important def length def finalDestination = 180 def vat(g) {1.175 * g}- Description
- A keyword which may precede declaration of a user method
or variable.
Methods need not be defined before they are called.
A method declared with
defalways produces a result. - Variables are declared before usage.
- Syntax
-
{annotations} {modifiers} def propertyName {annotations} {modifiers} def propertyName = expression {annotations} {modifiers} def methodName({parameters}) {{statements}} - Associated keywords