Skip to content
Ken Kousen edited this page May 21, 2020 · 5 revisions

Groovy For Java Developers

Safari Books Online, https://www.safaribooksonline.com/

This document is for notes that come up during class. It’s also an easy way to share code and other materials.

Non-Java languages on the JVM:

  • Groovy, www.groovy-lang.org

  • Scala

  • Clojure

  • Kotlin, www.kotlinlang.org

Groovy is a compiled language, even though we will write some "scripts"

Groovy Slack channel: http://groovycommunity.com/

All we need for setup is a Java SDK (JDK) version 1.8 or above and a Groovy installation

Version number summary:

  • Current stable version in the 3.0 line is 3.0.4

  • Current stable version in the 2.5 line is 2.5.12

Groovy 3:

  • Significant compiler redesign → Parrot Parser, support all Java 8 syntax

  • Requires Java 8 as the minimum Java version

Import GitHub repository into IDE

IntelliJ

Import the build.gradle file

  1. Use Open if an existing project is open, or Import otherwise

  2. Navigate to the build.gradle file in the root of the project

  3. Accept all the defaults in the Import wizard

Eclipse

Create an Eclipse project and import it

  1. From a command prompt, execute >gradlew cleanEclipse eclipse

  2. Use File → Open → General → Existing Projects Into Workspace → navigate to the root of the project and select it

Notes

  • static typing → types are known at compile time

    • Java, Scala, Kotlin

  • dynamic typing → types are inferred at run time

    • JavaScript, Python, Clojure

  • Groovy → optional typing

    • if you know the type (or care), specify it

    • if you don’t know or don’t care, use def

  • Normal practice suggests you use def less than 10% of the time

    • Most of the time, "if you’re typing and know the type, type it" (pun intended) — Dierk Koenig

    • It’s nice to have def available when you need it

Wait, isn’t def just an Object reference?

  • Yes, but Groovy also has Duck typing (term from Ruby) "If it walks like a duck and it quacks like a duck, it’s a duck"

In Java, if I use an Object ref, I can only invoke Object methods (unless I cast)

In Groovy, with a def type, I can invoke any method (or property) I like

  • if it’s there at runtime, we’re fine

  • Otherwise we’ll throw a MissingMethodException

Clone this wiki locally