1. 程式人生 > >2.3Groovy靈活的引數初始化

2.3Groovy靈活的引數初始化

package learn

class Robot {
    def type, height, width
def access(Map location, weight, fragile) {
        println "Received fragile? $fragile, weight: $weight, loc:$location"
}
}

    robot = new Robot(type: 'arm', width: 10, height: 40)
    println "$robot.type, $robot.height, $robot.width"
robot.access(x
: 30, y: 20, z:10, 50, true ) robot.access(50, true, x: 30, y: 20, z: 10)
執行結果:

arm, 40, 10
Received fragile? true, weight: 50, loc:[x:30, y:20, z:10]
Received fragile? true, weight: 50, loc:[x:30, y:20, z:10]

程式分析:

1、屬性為鍵值對,如:

robot = new Robot(type: 'arm', width: 10, height: 40)

2、access方法中的第一個形參預設接受鍵值對的實參,後面的引數安裝順序接受。

3、access方法中的第一個引數是map型別,可以省略(不建議,以免混淆)。