differences with java

default imports.

部分包和类默认已经import

multi-methods | runtime dispatch

groovy:method chosen at runtime base on types of arguments
java: method chosen at compile time base on declared types

Array initializers

{ } block is reserved for closures
使用中括号[]

  1. int[] array = [1,2,3]

可见域

java: 默认是 ‘package private’
groovy: 默认是public

semicolon is optional

parentheses is optional

  • 普通调用,括号可要可不要
  • 对于closure来说,不写括号是对closure的引用。带括号是对closure的调用
  • 当函数调用嵌套是,需要括号

return keyword is optional

最后的值会被返回

  • No matter what type of object we try to return, the return type defined in the method will determine the type that is actually returned
  • However, if the method uses the def keyword as its return type, then the return type is considered to be dynamic
  • No matter what value is contained in the last statement in a method, if the return type is void, the value returned will always be null

dynamic type

  • explicit type
  • use def keyword, decide at runtime later
    def basicVar() {
        //Groovy中支持动态类型,即定义变量的时候可以不指定其类型。Groovy中,变量定义可以使用关键字def。注意,虽然def不是必须的,但是为了代码清晰,建议还是使用def关键字
        def variable1 = 1   //可以不使用分号结尾
        def varable2 = "I ama person"
        def int x = 1  //变量定义时,也可以直接指定类型

        //Groovy对字符串支持相当强大,充分吸收了一些脚本语言的优点:
        //单引号''中的内容严格对应Java中的String,不对$符号进行转义
        defsingleQuote = 'I am $ dolloar'  //输出就是I am $ dolloar
        //双引号""的内容则和脚本语言的处理有点像,如果字符中有$号的话,则它会$表达式先求值。
        defdoubleQuoteWithoutDollar = "I am one dollar" //输出 I am one dollar
        def xx = 1
        defdoubleQuoteWithDollar = "I am $x dolloar" //输出I am 1 dolloar
        //三个引号'''xxx'''中的字符串支持随意换行 比如
        defmultieLines = ''' begin
     line  1
     line  2
     end '''
        //最后,除了每行代码不用加分号外,Groovy中函数调用的时候还可以不加括号。比如:
        println("test")
        println "test"
    }

    //函数定义时,参数的类型也可以不指定。比如
    String testFunction(arg1, arg2) {//无需指定参数类型
        //...
    }

    // 除了变量定义可以不指定类型外,Groovy中函数的返回值也可以是无类型的。比如:
    //无类型的函数定义,必须使用def关键字
    def nonReturnTypeFunc() {
        last_line   //最后一行代码的执行结果就是本函数的返回值
    }

    //如果指定了函数返回类型,则可不必加def关键字来定义函数
    String getString() {
        return "I am a string"
    }

    //函数返回值:Groovy的函数里,可以不使用returnxxx来设置xxx为函数返回值。如果不使用return语句的话,则函数里最后一句代码的执行结果被设置成返回值。比如
    //下面这个函数的返回值是字符串"getSomething return value"
    def getSomething() {
        "getSomething return value" //如果这是最后一行代码,则返回类型为String
        1000//如果这是最后一行代码,则返回类型为Integer
    }

ARM blocks

ARM (Automatic Resource Management) block

source file contain both class definitions and inline scripting.

  • when compile, generate a class object for each Groovy class
  • generate a class for scripting elements
  • Groovy scripts have a special binding for variable references

GroovyBeans || POGO (Plain Old Groovy Object)

  • Groovy automatically generates getters and setters for instance fields in a class that have the default visibility of public.
  • It also generates a default constructor.
  • field dereference operator @. directly access the field without going through a getter or setter

GroovyBeans && map

  • every groovybean has default built-in Map constructor
  • map中如果包含有不相关的属性,会直接抛异常

Autoboxing

  • as if primitives don’t exist
  • treat any numeric value as if both an object-base numeric and a primitive

Strings

  • Normal strings in Groovy are instances of the java.lang.String class
  • Strings that contain the ${…} syntax are instantiated as Groovy GString objects

Closures, on the other hand, can reference variables from outside their own scope

given: "a variable in scope"
       def greeting = "Hello"
   and: "a closure that can access the variable"
       def greet = { println "$greeting, World!"}
   when: "we invoke the closure with variable different"
       greet()
       greeting = "Goodbye"
       greet()
   then: "the output is as expected"
       """Hello, World!
   Goodbye, World!""" == output()

Groovy Truth (true/false)

  • 非0都是true
  • null 空值,空串,空的集合都是false, 否则都是true

<=> , Spaceship operator

Spaceship is a shorthand operator that works the same as Java’s compareTo method.

Spaceship operator && Elvis operator 组合, amazing

spaceship is a shorthand operator that works the same as Java’s compareTo method.

  • if they are equal, return 0
  • if first less than second, return -1
  • if first is greater than second, return 1

switch语句应用

  • 普通值,ex:数字、字符串
  • 逻辑表达式
  • 列表(判断是否在列表中),ex: [“apple”, “banana”]
  • map(判断是否在map中), ex:[a: 1, b: 2]
  • Range, ex:1..5

集合

  • Range, ex: 1..10, ‘a’..<’e’, Range有两个属性:from & to
  • List, list可以使用多个方法:plus, minus, left shift, flatten,any, every
  • Map, 任何有hashcode的对象都可以作为key
    /**
     * collection in groovy: List Map Range
     */
    def listInGroovy() {
        def aList = [5, 'String', true] //元素可以使任何对象
        assert aList[1] == 'String'
        assert aList[5] == null
        aList[100] = 100
        println aList.size //101
    }

    def rangeInGroovy() {
        def aRange = 1..5
        def aRangeWithoutEnd = 1..<5
        println aRange.from
        println aRange.to
    }

    def mapInGroovy() {
        def aMap = ['key1': 'value1', 'key2': true]

        def bMap = [:] //Map由[:]定义,注意其中的冒号。冒号左边是key,右边是Value。key必须是字符串,value可以是任何对象。另外,key可以用''或""包起来,也可以不用引号包起来。比如
        def newMap = [key1: "value1", key2: "value2"]

    }

operator

  • *. , spread-dot operator, 通常用于集合中所有元素一起调用函数或者访问属性
  • *, 展开集合

Power Groovy DSL Features

Named parameters