Saturday 2 August 2014

Setting up Groovy environment

What is Groovy?

Groovy is a dynamic language that runs on the JVM and is tightly integrated with the Java language.  Groovy provides lots of simplifications compared to standard Java language features and advanced language features as properties, closures, native support for lists, maps and regular expressions, duck typing and the elvis operator.


Setting up groovy environment

Groovy requires Java, so you need to have a version available (while groovy 1.6 supported JDK 1.4 or greater, for groovy 1.7 onwards, minimum JDK 1.5 is needed)

Download the latest version from Groovy.  Unzip it and put it in some folder on your hard drive.
Then you have to set the GROOVY_HOME environment variable and add %GROOVY_HOME%/bin  to your PATH variable (Similar to JAVA_HOME. See above link on how to set up java environment).

Open groovyConsole.bat by double clicking on the icon in the bin directory of the Groovy distribution. If that does not work you may want to open the command line, navigate to bin directory and execute the bat file. Even if it does not open you will see the errors responsible for not starting the bat file.

Type in println("Hello World from yourName!")  and you should see it printed on the console (screenshot attached). After typing do Ctrl + R to execute the code.



Loading external jars in Grrovy

If you see your groovy-2.3.6\conf folder you will see groovy-starter.conf file which looks like - 


And if you notice it loads jars from
  1. {groovy.home}/lib/*.jar or
  2. !{user.home}/.groovy/lib/*.jar
You can put your jars in any of the above folder. Also .gradle folder should be automatically be created in your user directory. For me it's C:\Users\athakur\.groovy.

Difference between Groovy and Java

  •  In Java 'java.lang' package is imported by default, but in groovy some others general purpose packages and classes are imported by default. Eg   
    • groovy.lang.*,
    • groovy.util.*,
    • java.io.*,
    • java.net.*,
    • java.util.*,
    • java.lang.*
  • In Java '==' operator is used for comparing primitive types and .equals is used to compare Objects but in grooby we can use '==' to compare both primitive and objects.
  • Semicolon is optional in groovy
  • In groovy all classes and methods and public by default.
  • Array is initialized as int[] array = [1,2,3] in groovy unlike Java where you do int[] array = { 1, 2, 3}.
  • In groovy you need to specify a variable of it is primitive or instance of some class. All you have to do is use keyword 'def' and groovy is smart enough to understand the instance type. Eg. def str = "Hello World!"
  • The return keyword is optional.
  • You can use the this keyword inside static methods (which refers to this class).
     

Reference to more information 

No comments:

Post a Comment

t> UA-39527780-1 back to top