Android系统学习-Groovy语言

发现一个学习Groovy非常好的网站,有编程经验的童鞋可以在15分钟学完这门语言:
原文链接


/*

  Set yourself up:

  1) Install SDKMAN - http://sdkman.io/

  2) Install Groovy: sdk install groovy

  3) Start the groovy console by typing: groovyConsole

*/

//  Single line comments start with two forward slashes

/*

Multi line comments look like this.

*/

// Hello World

println "Hello world!"

/*

  Variables:

  You can assign values to variables for later use

*/

def x = 1

println x

x = new java.util.Date()

println x

x = -3.1499392

println x

x = false

println x

x = "Groovy!"

println x

/*

  Collections and maps

*/

//Creating an empty list

def technologies = []

/*** Adding a elements to the list ***/

// As with Java

technologies.add("Grails")

// Left shift adds, and returns the list

technologies << "Groovy"

// Add multiple elements

technologies.addAll(["Gradle","Griffon"])

/*** Removing elements from the list ***/

// As with Java

technologies.remove("Griffon")

// Subtraction works also

technologies = technologies - 'Grails'

/*** Iterating Lists ***/

// Iterate over elements of a list

technologies.each { println "Technology: $it"}

technologies.eachWithIndex { it, i -> println "$i: $it"}

/*** Checking List contents ***/

//Evaluate if a list contains element(s) (boolean)

contained = technologies.contains( 'Groovy' )

// Or

contained = 'Groovy' in technologies

// Check for multiple contents

technologies.containsAll(['Groovy','Grails'])

/*** Sorting Lists ***/

// Sort a list (mutates original list)

technologies.sort()

// To sort without mutating original, you can do:

sortedTechnologies = technologies.sort( false )

/*** Manipulating Lists ***/

//Replace all elements in the list

Collections.replaceAll(technologies, 'Gradle', 'gradle')

//Shuffle a list

Collections.shuffle(technologies, new Random())

//Clear a list

technologies.clear()

//Creating an empty map

def devMap = [:]

//Add values

devMap = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy']

devMap.put('lastName','Perez')

//Iterate over elements of a map

devMap.each { println "$it.key: $it.value" }

devMap.eachWithIndex { it, i -> println "$i: $it"}

//Evaluate if a map contains a key

assert devMap.containsKey('name')

//Evaluate if a map contains a value

assert devMap.containsValue('Roberto')

//Get the keys of a map

println devMap.keySet()

//Get the values of a map

println devMap.values()

/*

  Groovy Beans

  GroovyBeans are JavaBeans but using a much simpler syntax

  When Groovy is compiled to bytecode, the following rules are used.

    * If the name is declared with an access modifier (public, private or

      protected) then a field is generated.

    * A name declared with no access modifier generates a private field with

      public getter and setter (i.e. a property).

    * If a property is declared final the private field is created final and no

      setter is generated.

    * You can declare a property and also declare your own getter or setter.

    * You can declare a property and a field of the same name, the property will

      use that field then.

    * If you want a private or protected property you have to provide your own

      getter and setter which must be declared private or protected.

    * If you access a property from within the class the property is defined in

      at compile time with implicit or explicit this (for example this.foo, or

      simply foo), Groovy will access the field directly instead of going though

      the getter and setter.

    * If you access a property that does not exist using the explicit or

      implicit foo, then Groovy will access the property through the meta class,

      which may fail at runtime.

*/

class Foo {

    // read only property

    final String name = "Roberto"

    // read only property with public getter and protected setter

    String language

    protected void setLanguage(String language) { this.language = language }

    // dynamically typed property

    def lastName

}

/*

  Logical Branching and Looping

*/

//Groovy supports the usual if - else syntax

def x = 3

if(x==1) {

    println "One"

} else if(x==2) {

    println "Two"

} else {

    println "X greater than Two"

}

//Groovy also supports the ternary operator:

def y = 10

def x = (y > 1) ? "worked" : "failed"

assert x == "worked"

//Groovy supports 'The Elvis Operator' too!

//Instead of using the ternary operator:

displayName = user.name ? user.name : 'Anonymous'

//We can write it:

displayName = user.name ?: 'Anonymous'

//For loop

//Iterate over a range

def x = 0

for (i in 0 .. 30) {

    x += i

}

//Iterate over a list

x = 0

for( i in [5,3,2,1] ) {

    x += i

}

//Iterate over an array

array = (0..20).toArray()

x = 0

for (i in array) {

    x += i

}

//Iterate over a map

def map = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy']

x = ""

for ( e in map ) {

    x += e.value

    x += " "

}

assert x.equals("Roberto Grails Groovy ")

/*

  Operators

  Operator Overloading for a list of the common operators that Groovy supports:

  http://www.groovy-lang.org/operators.html#Operator-Overloading

  Helpful groovy operators

*/

//Spread operator:  invoke an action on all items of an aggregate object.

def technologies = ['Groovy','Grails','Gradle']

technologies*.toUpperCase() // = to technologies.collect { it?.toUpperCase() }

//Safe navigation operator: used to avoid a NullPointerException.

def user = User.get(1)

def username = user?.username

/*

  Closures

  A Groovy Closure is like a "code block" or a method pointer. It is a piece of

  code that is defined and then executed at a later point.

  More info at: http://www.groovy-lang.org/closures.html

*/

//Example:

def clos = { println "Hello World!" }

println "Executing the Closure:"

clos()

//Passing parameters to a closure

def sum = { a, b -> println a+b }

sum(2,4)

//Closures may refer to variables not listed in their parameter list.

def x = 5

def multiplyBy = { num -> num * x }

println multiplyBy(10)

// If you have a Closure that takes a single argument, you may omit the

// parameter definition of the Closure

def clos = { print it }

clos( "hi" )

/*

  Groovy can memoize closure results [1][2][3]

*/

def cl = {a, b ->

    sleep(3000) // simulate some time consuming processing

    a + b

}

mem = cl.memoize()

def callClosure(a, b) {

    def start = System.currentTimeMillis()

    mem(a, b)

    println "Inputs(a = $a, b = $b) - took ${System.currentTimeMillis() - start} msecs."

}

callClosure(1, 2)

callClosure(1, 2)

callClosure(2, 3)

callClosure(2, 3)

callClosure(3, 4)

callClosure(3, 4)

callClosure(1, 2)

callClosure(2, 3)

callClosure(3, 4)

/*

  Expando

  The Expando class is a dynamic bean so we can add properties and we can add

  closures as methods to an instance of this class

  http://mrhaki.blogspot.mx/2009/10/groovy-goodness-expando-as-dynamic-bean.html

*/

  def user = new Expando(name:"Roberto")

  assert 'Roberto' == user.name

  user.lastName = 'Pérez'

  assert 'Pérez' == user.lastName

  user.showInfo = { out ->

      out << "Name: $name"

      out << ", Last name: $lastName"

  }

  def sw = new StringWriter()

  println user.showInfo(sw)

/*

  Metaprogramming (MOP)

*/

//Using ExpandoMetaClass to add behaviour

String.metaClass.testAdd = {

    println "we added this"

}

String x = "test"

x?.testAdd()

//Intercepting method calls

class Test implements GroovyInterceptable {

    def sum(Integer x, Integer y) { x + y }

    def invokeMethod(String name, args) {

        System.out.println "Invoke method $name with args: $args"

    }

}

def test = new Test()

test?.sum(2,3)

test?.multiply(2,3)

//Groovy supports propertyMissing for dealing with property resolution attempts.

class Foo {

  def propertyMissing(String name) { name }

}

def f = new Foo()

assertEquals "boo", f.boo

/*

  TypeChecked and CompileStatic

  Groovy, by nature, is and will always be a dynamic language but it supports

  typechecked and compilestatic

  More info: http://www.infoq.com/articles/new-groovy-20

*/

//TypeChecked

import groovy.transform.TypeChecked

void testMethod() {}

@TypeChecked

void test() {

    testMeethod()

    def name = "Roberto"

    println naameee

}

//Another example:

import groovy.transform.TypeChecked

@TypeChecked

Integer test() {

    Integer num = "1"

    Integer[] numbers = [1,2,3,4]

    Date date = numbers[1]

    return "Test"

}

//CompileStatic example:

import groovy.transform.CompileStatic

@CompileStatic

int sum(int x, int y) {

    x + y

}

assert sum(2,5) == 7

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 211,817评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,329评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,354评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,498评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,600评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,829评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,979评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,722评论 0 266
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,189评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,519评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,654评论 1 340
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,329评论 4 330
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,940评论 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,762评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,993评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,382评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,543评论 2 349