1.枚举enum
enum CoffeeSize{ SHORT, SMALL, MEDIUM, LARGE, MUG } def orderCoffee(size){ print "Coffee order received for size $size:" switch(size){ case [CoffeeSize.SHORT, CoffeeSize.SMALL]: println ‘Conscious‘ break; case CoffeeSize.MEDIUM..CoffeeSize.LARGE: println ‘Programmer‘ break; case CoffeeSize.MUG: println ‘Caffeine IV‘ break; } } orderCoffee(CoffeeSize.SMALL) orderCoffee(CoffeeSize.LARGE) orderCoffee(CoffeeSize.MUG) for(size in CoffeeSize.values()){ println size } /*output Coffee order received for size SMALL:Conscious Coffee order received for size LARGE:Programmer Coffee order received for size MUG:Caffeine IV SHORT SMALL MEDIUM LARGE MUG */
2.for-each循环
def list = [1,3,6,4,9] println ‘传统for循环‘ for(int i = 0; i < list.size(); i++){ println i } println ‘实现了 Iterable接口的for循环‘ for(int i : list){ println i } println ‘不指定类型的for循环‘ for(i in list){ println i } /*output 传统for循环 0 1 2 3 4 实现了 Iterable接口的for循环 1 3 6 4 9 不指定类型的for循环 1 3 6 4 9 */
3.变长参数
def receiveVarArgs(int a, int...b){ println "$a and $b" } def receiveArray(int a, int[] b){ println "$a and $b" } receiveVarArgs(1,2,3,4,5) receiveArray(1,2,3,4,5) /*output 1 and [2, 3, 4, 5] 1 and [2, 3, 4, 5] */
4.注解[email protected]
class Worker{ def Work(){println ‘Work‘} def Analyze(){println ‘Analyze‘} def WriteReport(){println ‘WriteReport‘} } class Expert{ def Analyze(){println ‘Expert Analyze‘} } class Manager{ @Delegate Expert expert = new Expert() @Delegate Worker worker = new Worker() } def ironcrow = new Manager() ironcrow.Work() ironcrow.Analyze() ironcrow.WriteReport() /*output Work Expert Analyze WriteReport */
5-注解@Lazy:惰性创建
// 非惰性创建 class Heavy { def size = 10 Heavy(){ println("Create Heavy with $size") } } class AsNeeded { def value Heavy heavy1 = new Heavy() Heavy heavy2 = new Heavy(size: value) AsNeeded(){ println ‘Created AsNeeded‘ } } class Program { static void main(String[] args){ def asNeeded = new AsNeeded(value: 1000) println asNeeded.heavy1.size println asNeeded.heavy1.size println asNeeded.heavy2.size println asNeeded.heavy2.size } } /*output Create Heavy with 10 Create Heavy with 10 Created AsNeeded 10 10 null null */
// 惰性创建 class AsNeeded { def value @Lazy Heavy heavy1 = new Heavy() @Lazy Heavy heavy2 = new Heavy(size: value) AsNeeded(){ println ‘Created AsNeeded‘ } } /*output Created AsNeeded Create Heavy with 10 10 10 Create Heavy with 10 1000 1000 */
[email protected]单例
@Singleton(lazy = true) class TheUnique{ def sayHello(){ println ‘hello‘ } } TheUnique.instance.sayHello() /*output hello */
时间: 2024-10-29 19:09:59