1.变量的定义和赋值
def param
type param
(param1,param2,param3) = [1,2,3]
//注: 句尾分号可有可无
2.包的导入
import com.a.b
//解决命名冲突使用as关键字
import com.a.b.C as AC
import com.b.b.C as BC
AC ac
BC bc
3.数组及循环定义
a.顺序数组: 1..3 ,1..<5 type IntRange
b.离散数组:[1,2,4,6] as int[]
c. for (i in 1..3) {} ,for (i = 0; i < 10; i++)
d.3.times {}
e. 3.upto(5) {}4.空指针及异常判断
a.Object?.exec()
b.try { //TODO }catch(ex) {//TODO}5.用接口封装闭包(单方法接口)
interface Listener {
void perform()
}
def function(Listener listener) {
listener.perform()
}
function ({//TODO} as Listener)
//闭包对象将被封装到Listener的perform方法中对于多方法接口的闭包传递方法(MAP类):
handle = [perform1 : {//TODO},perform2:{//TODO}]
function (handle as Listener) 动态调用动态类型
def types = ['ActionListener1','ActionListener2']
def handle = {println it}
for (i in types) {
handleImpl = handle.asType("com.test.$i")
obj."add$i"(handleImpl)
}6.运算符重载
<<: leftShift(other)
+: plus(other)7.switch语句:
switch (state) {
case [state1,state2]:
break;
case state3:
break;
}8.动态类型调用
class Man {
def sayHello() {//TODO}
}
class Woman {
def sayHello() {//TODO}
}
function (person) {
person.sayHello()
}
本文详细介绍编程中的变量定义与赋值、包的导入方法、数组及其循环的定义方式、空指针与异常处理机制、接口与闭包的使用技巧、动态类型的调用方式、运算符的重载方法以及switch语句的使用等核心概念。
1676

被折叠的 条评论
为什么被折叠?



