User-defined Types
- Sometimes, you might want to define your own types according to your business needs.
- We provide two features to achieve this.
Class
classis used to group related fields together. For example, you might want to define anEmployeeclass to group all information about an employee.
def class Employee {
def string name;
def string dept;
def real salary;
}
- In the above example you have created a class named
Employeethat has three different fields. Note that you still haven't created any variable ofEmployeetype. You can do this via:
Employee john;
Employee jane;
- In this way, we can create two
Employeetype variablesjohnandjane. Now, you might be asking how do I put the Jane's salary injane. There are many ways to achieve this:- Using JSON
-
Employee john = {
"name": "John Doe",
"dept": "HR",
"salary": 45000.0
};
Employee jane = {
"name": "Jane Doe",
"dept": "Engineering",
"salary": 71000.0
}; - As seen above, using JSON syntax, you can directly assign values to variables;
-
- Using
newand dot notation.- Sometime you don't know all the values of variable and may want to provide them when you have them. You can use
newand dot notation for that. -
Employee john = new Employee();
john.name = "John Doe";
john.dept = "HR";
john.salary = 45000.0;
Employee jane = new Employee();
jane.name = "Jane Doe";
jane.dept = "Engineering";
jane.salary = 71000.0; - The above example achieves the same result as the example when using JSON.
- Sometime you don't know all the values of variable and may want to provide them when you have them. You can use
- Using JSON
- As you can see, classes can be used to group all related data together. This can reduce clutter and helps with long term maintainability.
Alternative Syntax
You can use objectBlueprint instead of class.
Enum
enum(short for enumeration) is used when a variable can only have one of some possible values.- For example, in the
classexample we defineddepartmentfield to be astringtype. What if someone gives it the valueHuman Resourcesinstead ofHR. Now at every place where you check if the department isHR, you'll have to check for bothHuman ResourcesandHRvalues. As you can see, this can very quickly lead to all kinds of chaos and bugs. To avoid this, you can use enums.
def enum Department {
HR("HR"),
Engineering("Engineering"),
Accounting("Accounting"),
}
def Department myDepartment = Department.Engineering;
def Department myFriendsDepartment = Department.Accounting;
- In the above example
- You first defined an
enum Departmentwith three possible values - Then you created two variables of
Departmenttype- myDepartment with value
Department.Engineering - myFriendsDepartment with value
Department.Accounting
- myDepartment with value
- You first defined an
- As you can see, enums can be used to restrict the values that a variable can have.
Alternative Syntax
You can use categoryBlueprint instead of enum.