Groovy基础教程

2020-02-07  本文已影响0人  陈道乐

特性

基础数据类型

和java相同,感觉最大的区别也就是多了一个def

数组

def array = [0, 1, 2, 3]
//or
int[] array = [0, 1, 2, 3]
//or
def array = 0..3

映射

 //注意支持不同的数据类型的value 
 def mp = ["fist": 1, "second": "2"]
 mp.each {println "key: ${it.key}, value: ${it.value}"}

流程控制

1.if

和java相同

if(statement) {
    //TODO
} 


if (statement) {
    
} else {
    
}

2. switch

和java相同

switch(expression) {
    case 1:
    //TODO:something
    break;
    
    default:
    //TOOD:
}

3.while

和java相同

while(statement) {
    
}

4.for

无感了,也是和java相同

for(variable declaration;expression;Increment) {
    //TODO:something
}

5.for-in

新增的一个东西,有点意思了,怎么看在 javascript中有点眼熟

int[] array = [0, 1, 2, 3, 4]

for(int i in array) {
    
}

//这里开始和范围预算福结合在一起了
for(int i in 0..5) {
    
}

运算符

1.范围运算符


//打印出来有可能也是显示 1..5 ,但是这种意义就不同了,可以简单认为是数组[1, 2, 3, 4, 5]    
//使用get方式用下标获取元素。
def x = 1..5;
println(x);
println(x.get(0))


//这种定义方式表示的是 1、2、3、4 不包含5
def x = 1..<5


//同时也是支持倒序的
def x = 5..1


//这里我也蒙蔽了,竟然支持字符,同样也有倒序的支持
def x = 'a'..'x'

语法

1.类

结构和java相似, 继承 和 实现两个方式都有

//引入包的方式相同,同时兼容java包
import xxx.xxx.xx

class Person {
    //使用def关键字定义标识符,在groovy里面还是用标识符称呼比较合适
    def name = "xiaoming"
    
    static void main(String[] args) {
        //TODO: something
    }
}

2.方法

class MyClass {
    //这是一个相对java来说相对极端的例子, 不确定的输入类型,但是要提供相同的参数数量
    //同时也有不确定的返回类型, 可以用def来表示不确定的返回类型。不确定指的的是是否存在和不确定的数据类型
    //也可以制定默认参数
    def foo(arg1, arg2, arg3 = 0) {
        
    }
}

==闭包==

这里比较重要, 怎么看怎么像lambda表达式

1.基础

//这里是简单的使用,不带参数的
class MainClient {
    static void main(String[] args) {
        def foo = {println "hello world"}
        foo.call()
    }
}

//带参数的,看起来有点意思
class MainClient {
    static void main(String[] args) {
        def foo = {param -> println "hello ${param}"}
        foo.call("world")
    }
}

//闭包里面可以引用外部参数
class MainClient {
    static void main(String[] args) {
        def str = "hello"
        def foo = {param -> println "${str} ${param}"}
        foo.call("world")

        str = "welcome"
        foo.call("world")
    }
}


//同时闭包也可以做参数传递
class MainClient {
    static void main(String[] args) {
        def str = "hello"
        def foo = {param -> println "${str} ${param}"}
        fooCall(foo)
    }

    static void fooCall(clo) {
        clo.call("world")
    }
}

2.遍历

def array = [0, 1, 2, 4]
//看了一下 each源码,一个数组的静态方法,本质上通过while遍历出数据,分别调用闭包方法
array.each{ i -> println i}

IO读写

这里已经开始涉及到语言上层的API了

    //写文件
    new File("test.dat").withWriter("utf-8") {
        writer -> writer.writeLine "hello world"
    }
    
    //读文件
    new File("test.dat").each {
        line -> println line
    }

注解

与java类似,这里就不详细说明了, 可以看我后面写文章

上一篇 下一篇

猜你喜欢

热点阅读