Android系統(tǒng)學(xué)習(xí)-Groovy語言

發(fā)現(xiàn)一個(gè)學(xué)習(xí)Groovy非常好的網(wǎng)站捐康,有編程經(jīng)驗(yàn)的童鞋可以在15分鐘學(xué)完這門語言:
原文鏈接


/*

  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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末缎脾,一起剝皮案震驚了整個(gè)濱河市袭灯,隨后出現(xiàn)的幾起案子衷笋,更是在濱河造成了極大的恐慌,老刑警劉巖模庐,帶你破解...
    沈念sama閱讀 219,427評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件贞盯,死亡現(xiàn)場離奇詭異,居然都是意外死亡氯哮,警方通過查閱死者的電腦和手機(jī)际跪,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,551評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來蛙粘,“玉大人垫卤,你說我怎么就攤上這事〕瞿粒” “怎么了穴肘?”我有些...
    開封第一講書人閱讀 165,747評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長舔痕。 經(jīng)常有香客問我评抚,道長,這世上最難降的妖魔是什么伯复? 我笑而不...
    開封第一講書人閱讀 58,939評論 1 295
  • 正文 為了忘掉前任慨代,我火速辦了婚禮,結(jié)果婚禮上啸如,老公的妹妹穿的比我還像新娘侍匙。我一直安慰自己,他們只是感情好叮雳,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,955評論 6 392
  • 文/花漫 我一把揭開白布想暗。 她就那樣靜靜地躺著,像睡著了一般帘不。 火紅的嫁衣襯著肌膚如雪说莫。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,737評論 1 305
  • 那天寞焙,我揣著相機(jī)與錄音储狭,去河邊找鬼互婿。 笑死,一個(gè)胖子當(dāng)著我的面吹牛辽狈,可吹牛的內(nèi)容都是我干的慈参。 我是一名探鬼主播,決...
    沈念sama閱讀 40,448評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼刮萌,長吁一口氣:“原來是場噩夢啊……” “哼懂牧!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起尊勿,我...
    開封第一講書人閱讀 39,352評論 0 276
  • 序言:老撾萬榮一對情侶失蹤僧凤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后元扔,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體躯保,經(jīng)...
    沈念sama閱讀 45,834評論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,992評論 3 338
  • 正文 我和宋清朗相戀三年澎语,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了途事。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,133評論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡擅羞,死狀恐怖尸变,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情减俏,我是刑警寧澤召烂,帶...
    沈念sama閱讀 35,815評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站娃承,受9級特大地震影響奏夫,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜历筝,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,477評論 3 331
  • 文/蒙蒙 一酗昼、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧梳猪,春花似錦麻削、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,022評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至惕稻,卻和暖如春竖共,著一層夾襖步出監(jiān)牢的瞬間蝙叛,已是汗流浹背俺祠。 一陣腳步聲響...
    開封第一講書人閱讀 33,147評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人蜘渣。 一個(gè)月前我還...
    沈念sama閱讀 48,398評論 3 373
  • 正文 我出身青樓淌铐,卻偏偏與公主長得像,于是被迫代替她去往敵國和親蔫缸。 傳聞我的和親對象是個(gè)殘疾皇子腿准,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,077評論 2 355