2.3Groovy灵活的参数初始化

来源:互联网 发布:数据库数据存储方式 编辑:程序博客网 时间:2024/06/15 07:17

package learnclass 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类型,可以省略(不建议,以免混淆)。

原创粉丝点击