How Write a Custom Method inside of a Class in Groovy?

Problem scenario
You are familiar with Groovy scripts. Now you want to use a class and a method in the class. How do you do this?

Solution
Prerequisites
Install Groovy. See these directions for Ubuntu/Debian if you need assistance; see these directions for CentOS.

Procedures

  1. Create a file called test.groovy with the content below:
class Example {
   def static Display(nifty) {
      nifty.call("Red");
   }

   static void main(String[] args) {
      def str1 = "Cool attempt: ";
      def contint = { param -> println "${str1} ${param}" }
      contint.call("Blue");

      str1 = "Attempt: ";
      contint.call("Yellow");

      Example.Display(contint);
   }
}

2. Run it with this: groovy test.groovy

3. You are done. You see the ".call" syntax to invoke a method and pass a parameter.

Leave a comment

Your email address will not be published. Required fields are marked *