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?

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


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

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

      str1 = "Attempt: ";"Yellow");


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 *