Created
March 17, 2015 03:03
-
-
Save fmamud/3160d37e6a20b303bf9f to your computer and use it in GitHub Desktop.
02-groovy-for-java-devs.groovy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
________________ ______ | |
/ ____/_ __/ __ \ / ____/________ ____ _ ____ __ | |
/ /_ / / / / / / / / __/ ___/ __ \/ __ \ | / / / / / | |
/ __/ / / / /_/ / / /_/ / / / /_/ / /_/ / |/ / /_/ / | |
/_/ /_/ /_____/ \____/_/ \____/\____/|___/\__, / | |
/____/ | |
12/03/2015 | |
@ftmamud | |
https://friendstechday.wordpress.com/ | |
Differences from Java | |
*/ | |
// Compare Java Bean & Groovy Bean | |
// Public by default | |
// Getters and Setters | |
def p = "FTD" | |
def showEvent(what) { | |
println what | |
} | |
showEvent(p) | |
// default | |
class Pessoa { | |
Integer id | |
String name | |
def getId() { | |
"" | |
} | |
} | |
def p = new Pessoa(id:1, name:"Groovy") | |
println p.id | |
p.name = "Java" | |
println "$p.id $p.name" | |
// Return keyword optional | |
/* Groovy Default imports \o/ | |
java.io.* | |
java.lang.* | |
java.math.BigDecimal | |
java.math.BigInteger | |
java.net.* | |
java.util.* | |
groovy.lang.* | |
groovy.util.* | |
*/ | |
new File(".").absolutePath | |
/* Groovy Script Binding | |
String eventName = "ftd" | |
void showEventName(){ | |
assert eventName == "ftd" // Not allowed ! | |
} | |
showEventName() | |
*/ | |
// def or Object (Multi-methods: override methods problems) | |
class Printador { | |
void print(String texto) { | |
println "String $texto" | |
} | |
void print(Object texto) { | |
println "Object $texto" | |
} | |
} | |
Object texto = "Vamos embora?" | |
new Printador().print(texto) | |
def show(obj) { | |
println obj | |
} | |
show(o) | |
// GDK - http://groovy-lang.org/gdk.html | |
String.metaClass.ftd = { | |
"Groovy Rocks!" | |
} | |
"Qual linguagem domina?".ftd() | |
[1,2,3,4,5].sum() | |
// Class first citizen (properties) | |
println String.properties | |
// Array initializers | |
//Java way: int[] arr = new int[] { 1,2,3 }; | |
// Groovy way | |
int[] arr = [1,2,3] | |
arr.class | |
// Protected , @groovy.transform.PackageScope | |
import groovy.transform.PackageScope | |
class Person { | |
@PackageScope String name | |
} | |
// Automatic Resource Management : Try with resources | |
new File('names.txt').withReader('UTF-8') { reader -> | |
reader.eachLine { | |
println it | |
} | |
} | |
// Java 8 == Closures [1, 2, 3].stream() | |
[1,2,3].stream().map { it ** 2 }.forEach { println it } | |
// static with 'this' | |
// checked and unchecked exceptions | |
new File('names.txt').text | |
// newline at the wrong place into the code | |
myVariable = "FTD Groovy: " | |
+ 42 // this line has no effect*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment