【Groovy】Groovy 方法调用 ( Groovy 构造函数中为成员赋值 | Groovy 函数的参数传递与键值对参数 | 完整代码示例 )
生活随笔
收集整理的這篇文章主要介紹了
【Groovy】Groovy 方法调用 ( Groovy 构造函数中为成员赋值 | Groovy 函数的参数传递与键值对参数 | 完整代码示例 )
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 一、Groovy 構造函數中為成員賦值
- 二、Groovy 函數的參數傳遞與鍵值對參數
- 三、完整代碼示例
一、Groovy 構造函數中為成員賦值
Groovy 類沒有定義構造函數 , 但是可以使用如下形式的構造函數 , 為 Groovy 類設置初始值 ;
new 類名(成員名1: 成員值1, 成員名2: 成員值2)順序隨意 : 成員的順序隨意 , 沒有強制要求 , 只需要 成員名 與 成員值對應即可 ;
個數隨意 : 成員個數隨意 , 可以為所有的屬性賦值 , 也可以只為其中的部分屬性賦值 ;
如下代碼 :
class Student {def namedef age }// 實例化 Student 類 // 正常賦值 def student = new Student(name: "Tom", age: 18) // 顛倒順序賦值 def student2 = new Student(age: 16, name: "Jerry") // 只為 name 屬性賦值 def student3 = new Student(name: "Jim")// 打印兩個對象的值 println "student : ${student.name} , ${student.age}" println "student2 : ${student2.name} , ${student2.age}" println "student3 : ${student3.name} , ${student3.age}"執行結果為 :
student : Tom , 18 student2 : Jerry , 16 student3 : Jim , null二、Groovy 函數的參數傳遞與鍵值對參數
在 Groovy 的構造函數中 , 可以使用
成員名1: 成員值1, 成員名2: 成員值2類型的參數 , 這是鍵值對 map 類型的集合 ;
但是對于普通的函數 , 不能使用上述格式 , 如果出現
變量名1: 變量值1, 變量名2: 變量值2樣式的代碼 , 會將上述參數識別為一個 map 集合 ;
定義了一個 Groovy 類 , 其中定義的方法接收 222 個參數 ;
class Student {def namedef agedef printValue(a, b) {println "${a}, ${b}"} }如果使用 student.printValue(a: “Tom”, b: 18) , 就會報錯 , 提示只傳入了一個 map 集合作為參數 ;
必須使用如下形式 , 才能正確執行 printValue 函數 ;
// 傳入的 a: "Tom", b: 18 是第一個參數 , 這是一個 map 集合 // 第二個參數是 "Jerry" 字符串 student.printValue(a: "Tom", b: 18, "Jerry")三、完整代碼示例
完整代碼示例 :
class Student {def namedef agedef printValue(a, b) {println "${a}, ${b}"} }// 實例化 Student 類 def student = new Student(name: "Tom", age: 18) def student2 = new Student(age: 16, name: "Jerry") def student3 = new Student(name: "Jim")// 打印兩個對象的值 println "student : ${student.name} , ${student.age}" println "student2 : ${student2.name} , ${student2.age}" println "student3 : ${student3.name} , ${student3.age}"// 下面是錯誤用法 // a: "Tom", b: 18 參數代表了一個鍵值對集合 , 執行會報錯 // student.printValue(a: "Tom", b: 18)// 傳入的 a: "Tom", b: 18 是第一個參數 , 這是一個 map 集合 // 第二個參數是 "Jerry" 字符串 student.printValue(a: "Tom", b: 18, "Jerry")執行結果 :
student : Tom , 18 student2 : Jerry , 16 student3 : Jim , null [a:Tom, b:18], Jerry總結
以上是生活随笔為你收集整理的【Groovy】Groovy 方法调用 ( Groovy 构造函数中为成员赋值 | Groovy 函数的参数传递与键值对参数 | 完整代码示例 )的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Groovy】Groovy 方法调用
- 下一篇: 【Groovy】Groovy 方法调用