- groovy -e “println ‘Hello World’” - execute groovy code from comand line
- groovy Example.groovy - run groovy code from the file Example.groovy
- groovyc Example.groovy - compile groovy code from the file to the JVM class. Then you can run this code with JVM adding groovy libraries: java -classpath groovy-all.jar:. Example
- groovysh - interactive command line shell
- groovyConsole - interactive GUI shell
- Arithmetic:
- BigDecimal is used by default for number literal with fraction
- Number literals without fraction are the smallest type that fits Integer, Long, BigInteger
- Strings:
- Single quoted is standard java String
- Double quoted is GString (may contain groovy expressions, can be substring using [])
- Tripple quoted are multiline strings
- Slashy - no escaping needed - useful for regex
- Operator overloading - operators map to specific methods f.e. + is same ad method add()
- Method can be referenced as closure with .& operator
- Closures has properties:
- maximumNumberOfParameters - number of parameters provided to closure
- parameterTypes - array of types of parameters
- Collection methods: collect - as map in Scala and inject as foldLeft
- Objects evaluate to false: null, empty collections, iterators, empty GStrings, numbers equals 0, non-matching regexp pattern matchers, everything else evaluete to true
- == is treated as equals() in java but null safe. If objects implement Comparable then compareTo method is used
- a.is(b) - for java ==
- string.contains(gstring) is false due to internal equals method usage
- Null-safe operator returns null without futher evaluation in case od null ?.
- Elvis operator shorthand for returning default value ?:
- Spaceship operator <=> which replace compareTo method
- regexp operator ~ what creates a Pattern, =~ what creates Matcher, ==~ matching String against regexp
- spread operator *. is a shorthand for Collection.collect(closure)
- as operator transforms a variable to another type
- xml support with classes MarkupBuilder and XmlParser
- json suppert with JsonBuilder, JsonSlurper
- Integrations with java:
- Groovy shell - evaluates expressions in Java with passing in and out variables
- GroovyClassLoader - parse and compile classes
- Groovy Joint Compiler - compile all groovy and java sources. Allows circular dependencies between them, but on other layers
- Spring Groovy Integration - beans can be defined by POGO with lang namespace
- Changes between groovy and java:
- this inside static method refers to class
- do-while loops are not supperted
- all exceptions are unchecked
- inner classes are not allowed
- Built-in AST Transformations: @Singleton, @Delegate, @TupleConstructor, @TimedInterrupt
- @TypedChecked - analyze at compile-time
- @CompileStatic - compile like javac compiler, no groovy dynamic features
Sunday, 21 July 2013
Some groovy gotchas
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment