Groovy基础知识

Gradle是Android Studio中的主流构建工具。Gradle内置的Groovy是的一门JVM语言,最终编译成class文件在JVM虚拟机上运行。

《Groovy基础知识》

def:在Groovy中,通过def关键字来声明变量和方法,用def声明的类型Groovy会进行类型推断。

Groovy的特点

  • 语句后面的分号可省略;
  • 变量类型和方法参数类型可省略;
  • 调用方法的圆括号可省略;
  • 部分语句中的return可省略;
  • 所有的Class类型,可省略后面的.class;
  • Class类里,只要有属性,就默认有Getter/Setter,可省略之;
  • 同一个对象的属性操作,可用with代替:

示例:

def a = 1;//Groovy动态判断a类型为整型

def test(){
    println("hello world!");  //可写成 println "hello world!"
    return 1;  //可写成 1;不过建议少用
}

Test test = new Test(); 
test.id = 1;
test.name = "test";

//可写成
test.with{
    id = 1
    name = "test"
}

在Groovy中,类型是弱化的,所有的类型可动态推断,但类型不对仍会报错。

Groovy中的数据类型

  • Java基本数据类型和对象;
  • Closure闭包;
  • 加强型的List、Map等集合类型;
  • 加强型的File、Stream等IO类型;

单引号字符串

def result = 'a'+'b'

assert result == 'ab'

单引号字符串不支持占位符插值操作,但可通过”+”直接拼接。

assert断言,若assert为false则表示异常。

双引号字符串

def test = 'a'
def result = "hello, ${test}"

assert result.toString() == 'hello, a'

双引号字符串支持站位插值操作,一般用💲{}或者 💲表示。💲{}一般用于替换字符串或表达式,💲一般用于属性格式,如person.name,name是person的属性。

def person = [name:'jordon',age:28]
def result = "$person.name is $person.age years old"

assert result == 'jordon is 28 years old'

三引号字符串

def result = ''' 
line one
line two
line three
'''

三重单引号字符串允许字符串的内容在多行出现,新的行被转换为’\n’,其他所有的空白字符都被完整的按照文本原样保留。

加强型的List 和 Map

def array = [1,'a',true] //List中可存储任意类型

assert array[2] == true
assert array[-1] == 'a'//负数索引表示从右向左index

array << 2.3 //移位表示add元素

//选取子集合
assert array[1,3] == ['a',2.3]
assert array[1..3] == ['a',true,2.3]

//定义一个Map
def colors = [red:'#FF0000', green:'#00FF00']
assert colors['red'] == '#FF0000' == colors.red

def key = 'red'
assert colors[(key)] == '#FF000' //可以将一个变量或者类用()包起来作为key

保存在List中的对象不受类型限制,但Groovy中数组和Java中类似。Groovy中的Map的key可为任何对象,可以将一个变量或者类用()包起来作为key。

Closure闭包

由{ }包括起来的可执行的代码块或方法指针,可作为方法的参数或返回值,也可以作为一个变量存在。

//声明多参数闭包
def closureMethod1 = {a,b ->
    println "the word is ${a}${b}"
}

//声明隐含参数it闭包
def closureMethod2 = {
    println it
}

//外部调用闭包
closureMethod1.call(1,2)
closureMethod1(1,2)
closureMethod2()

//闭包作为方法test的参数调用
def test(name,password,Closure closure){
    println "it is a method"
}

test('admin','123456',{
    //do something by the Closure
})

闭包可以有返回值和参数,多个参数之间以 , 分割,参数和代码之间以-> 分割。closureMethod1就是闭包的名字。

如果闭包没定义参数,则默认隐含一个名为it的参数。

在Android studio中的编译运行Groovy

task(test){//任务名称 test
    println 'this is a good test'
    //to do something
}

//运行 命令行
gradle test

在Android Studio下的.gradle文件内编写task任务,执行其中的Groovy代码。

更多API调用可翻阅Groovy官网的API文档

    原文作者:正规程序员
    原文地址: https://www.jianshu.com/p/d96d66c727a4
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞