groovy基础
groovy基本语法groovy默认会导入以下库 import java.lang.*
import java.util.*
import java.io.*
import java.net.*
import groovy.lang.*
import groovy.util.*
import java.math.BigInteger
import java.math.BigDecimal
groovy语句可以不加分号; 数据类型Groovy提供多种内置数据类型。以下是在Groovy中定义的数据类型的列表
Groovy还允许其他类型的变量,如数组,结构和类,我们将在后续章节中看到。 定义变量有两种方式:普通java语法和def关键字 运算符感觉groovy支持java所有的运算符,优先级也是类似的。 class Example { static void main(String[] args) { def range = 5..10; println(range); println(range.get(2)); } } [5,6,7,8,9,10] 7
控制流程while和for语句的用法跟java一样。break和continue也支持。 class Example {
static void main(String[] args) {
int[] array = [0,1,2,3];
for(int i in array) {
println(i);
}
}
}
方法
- 通过def定义方法时,可不指定参数类型,可指定参数默认值。默认参数只能放在之后。def someMethod(parameter1,parameter2 = 0,parameter3 = 0) {
// Method code goes here
}
def通过def关键字定义的变量是动态类型的,跟脚本语言一样,只有在运行时才能确定。 字符串Groovy提供了多种表示String字面量的方法。 Groovy中的字符串可以用单引号(’),双引号(“)或三引号(”“”)括起来。此外,由三重引号括起来的Groovy字符串可以跨越多行。 class Example {
static void main(String[] args) {
String a = 'Hello Single';
String b = "Hello Double";
String c = '''Hello Triple" aa "Multiple lines''';
println(a);
println(b);
println(c);
println(sample[4]); // Print the 5 character in the string
//Print the 1st character in the string starting from the back
println(sample[-1]);
println(sample[1..2]);//Prints a string starting from Index 1 to 2
println(sample[4..2]);//Prints a string starting from Index 4 back to 2
}
}
范围范围是指定值序列的速记。范围由序列中的第一个和最后一个值表示,Range可以是包含或排除。包含范围包括从第一个到最后一个的所有值,而独占范围包括除最后一个之外的所有值。这里有一些范例文字的例子 - 1..10 - 包含范围的示例 序号 方法和描述 列表列表是用于存储数据项集合的结构。在Groovy中,List保存了一系列对象引用。List中的对象引用占据序列中的位置,并通过整数索引来区分。列表文字表示为一系列用逗号分隔并用方括号括起来的对象。 要处理列表中的数据,我们必须能够访问各个元素。 Groovy列表使用索引操作符[]索引。列表索引从零开始,这指的是第一个元素。 以下是一些列表的示例 - 面向对象groovy支持对象,继承,接口,内部类、抽象类的功能,用法跟java一样。 闭包闭包是一段代码。能够被执行,被传递,被存储。 class Example {
static void main(String[] args) {
def clos = {println "Hello World"};
clos.call();
def clos = {param->println "Hello ${param}"};
clos.call("World");
def clos = {println "Hello ${it}"};
clos.call("World");
def str1 = "Hello";
def clos = {param -> println "${str1} ${param}"}
clos.call("World");
def lst = [11,12,13,14];
lst.each {println it} // 闭包传递给each函数
def mp = ["TopicName" : "Maps","TopicDescription" : "Methods in Maps"]
mp.each {println it} // 定义闭包函数
mp.each {println "${it.key} maps to: ${it.value}"}
def lst = [1,3,4];
lst.each {println it}
println("The list will only display those numbers which are divisible by 2")
lst.each{num -> if(num % 2 == 0) println num} // 闭包中使用条件
}
}
闭包本身也提供了一些方法:比如find,any等 class Example {
static void main(String[] args) {
def lst = [1,4];
def value;
value = lst.find {element -> element > 2}
println(value);
}
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |