Packages and namespaces are used in Groovy to organize code into logical groups and avoid naming conflicts between classes and other identifiers. Here’s how to use packages and namespaces in Groovy:
1. Packages: A package is a group of related classes and other resources, such as interfaces and enums. In Groovy, you can define a package using the `package` keyword followed by the name of the package. Here’s an example:
package com.example.myapp class Person { String name int age void sayHello() { println("Hello, my name is $name and I am $age years old.") } } def person = new com.example.myapp.Person(name: "Alice", age: 30) person.sayHello()
In this example, we define a package called `com.example.myapp` and a class called `Person` inside that package. We create an instance of the `Person` class using the fully qualified class name, which includes the package name.
2. Namespaces: A namespace is similar to a package, but it can contain other types of identifiers besides classes, such as functions, variables, and constants. In Groovy, you can define a namespace using the `namespace` keyword followed by the name of the namespace. Here’s an example:
namespace com.example.myapp def greet(String name) { println("Hello, $name!") } greet("Alice")
In this example, we define a namespace called `com.example.myapp` and a function called `greet` inside that namespace. We call the `greet` function directly using its name, without needing to use the fully qualified name as we did with the `Person` class in the previous example.
Packages and namespaces are important concepts in Groovy programming, and they allow you to organize your code into logical groups and avoid naming conflicts. By using packages and namespaces, you can create code that is easier to read, maintain, and extend.