1. 程式人生 > >Groovy語言學習--語法基礎(1)

Groovy語言學習--語法基礎(1)

2018年11月末,從上家公司離職後進入現在的公司。進入專案以來,發現專案中有很多groovy指令碼,以前沒接觸過groovy,抽時間系統地學一下,也方便後期專案的開發和維護。

groovy和java的淵源以及和規則引擎的比較,作為白板目前還沒評論的資格,學語言當然還是直接擼程式碼來得實在。好在和java同宗,白板之旅。

 

package groovy

/*
 * Print方法 print println 後面必須跟引數 否則會拋groovy.lang.MissingPropertyException
 */

//print  
//println
println "helloworld"
/*
* 單引號中的內容嚴格對應java中的String 不對$符號進行轉義 */ def s1 = 'i am 100 $ dollar' println s1 class Person { String name Integer age } def person = new Person(name:"john",age:18) /* * 雙引號“”的內容和指令碼語言處理有點像,如果字元中有$符號的話,則會表示式先求值 */ def s2 = "i am 100 ${person.name} dollar" println s2 /* * 三個引號 三個單引號或三個雙引號 中的字串支援隨意換行 不同處""" """支援$等特殊符號轉義 ''' '''不支援,強String型別
*/ def s3 = """ tom is a good boy $s1 """ println s3 def s4 = ''' tom is a good boy $s1 ''' println s4 /** * 定義函式 */ //無參函式 def fun1() { } //有參函式,無需指定引數型別 def fun2() { }
//如果制定了函式返回型別,則可不必加關鍵字def 來定義函式 String fun3() { return "welcome" } //如果不使用return 來設定返回值 ,則函式裡最後一句程式碼的執行結果被設定成返回值 型別不匹配則會報錯 Integer fun4() { "a story" "about" "prince" //if this is end型別不匹配 GroovyCastException 4.0 //if this is a number will be return a Integer number 4 } println fun4() /* * assert 斷言 可以簡單理解為 比較 進行簡單的判斷 */ def str1 = "abc" assert str1.size() == 3 //assert str1.size() != 3 /* * 迴圈 */ for (int i =0;i<5;i++ ) { println i + "for 1" } for (i =0;i<5;i++ ) { println i + "for 2" } for (i in 4..8 ) { println i-4 + "for 3" } 5.times { println "circle" } /* *三目運算子 * */ def name def result =name != null?name :"name is error" println result /* * 異常 */ try { // 5/0 }catch(Exception e) { print e } try { // 5/0 }catch(anything) { print anything } /* * Switch */ def age = 36 def rate switch (age) { case 10..26: rate = 0.05 break case 27..36: rate = 0.06 break default: throw new Exception() } println rate /* * asType 資料型別轉換 */ def type1 = 100 def type2 = 200.00 def type3 = type2.asType(Integer) def type4 = type1.asType(String) println("groovy 語言學習--語法基礎(1) ---end ")