SlideShare une entreprise Scribd logo
1  sur  51
Télécharger pour lire hors ligne
Groovy on Android
Who are you?
def speaker = new SZJUG.Speaker(
name: 'Alexey Zhokhov',
employer: 'Scentbird',
occupation: 'Grails Developer',
github: 'donbeave',
email: 'alexey@zhokhov.com',
site: 'http://www.zhokhov.com',
description: """whole-stack engineer
(back-end, front-end, mobile, UI/UX)"""
)
Android on Gradle
Groovy is inside the Gradle
You probably know Groovy through Gradle already.
Groovy is a superset of Java.
It contains lots of cool stuff that makes Java fun!
So,
Why can Groovy be
Android' Swift?
Android N supports Java 8
"Android is in the Java stone age state"
But not released
Multi-faceted language:
Object-oriented
Dynamic
Functional
Static
Groovy is
Straightforward integration with Java.
Java on Android is very verbose
public class FeedActivity {
TextView mTextView;
void updateFeed() {
new FeedTask().execute("http://path/to/feed");
}
class FeedTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost(params[0]);
InputStream inputStream = null;
String result = null;
1/4
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
2/4
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (Exception squish) {
}
}
StringBuilder speakers = null;
try {
JSONObject jObject = new JSONObject(result);
JSONArray jArray = jObject.getJSONArray("speakers");
speakers = new StringBuilder();
for (int i = 0; i < jArray.length(); i++) {
speakers.append(jArray.getString(i));
speakers.append(" ");
}
3/4
} catch (JSONException e) {
// do something?
}
return speakers.toString();
}
@Override
protected void onPostExecute(String s) {
mTextView.setText(s);
}
}
}
4/4
So now,
let’s see the equivalent in Groovy
(no kidding either)
class FeedActivity {
TextView mTextView
void updateFeed() {
Fluent.async {
def json = new JsonSlurper().parse([:], new URL('http://path/to/feed'), 'utf-8')
json.speakers.join(' ')
} then {
mTextView.text = it
}
}
}
Because I'm lazy, I don't like to write a lot of code.
And Groovy helps me with that.
It's not only for writing less code,
it's also for cool features and good readability.
very consice language, actually
Semicolons
Parenthesis
return keyword
public keyword
Optional
Sugar syntax
1) Groovy truth
// if (s != null && s.length() > 0) { ...}
if (s) { ... }
// easy check for empty maps, list, empty strings
2) Elvis
def name = person.name ?: "unknown"
3) Save navigation
order?.lineItem?.item?.name
Where I have seen it?
Right, Apple's Swift
language was inspired by Groovy
4) List, maps (Groovy)
def shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
def occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
def emptyMap = [:]
def emptyList = []
4) List, maps (Swift)
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
var emptyMap = [:]
var emptyList = []
5) Named parameters (Groovy)
def triangleAndSquare =
new TriangleAndSquare(size: 10, name: "another test shape")
5) Named parameters (Swift)
var triangleAndSquare =
TriangleAndSquare(size: 10, name: "another test shape")
6) @Lazy annotation (Groovy)
class DataManager {
@Lazy importer = new DataImporter()
}
6) @Lazy annotation (Swift)
class DataManager {
@lazy var importer = DataImporter()
}
7) Closure (Groovy)
numbers.collect { int number ->
def result = 3 * numbers
return result
}
7) Closure (Swift)
numbers.map({
(number: Int) -> Int in
let result = 3 * number
return result
})
What else is cool in Groovy?
8) Builders import groovy.json.*
def json = new JsonBuilder()
json.conference {
name 'SZJUG'
subject 'Groovy on Android'
date 2016
time ['13:00', '16:00']
address {
place 'GRAPE 联合创业空间'
street '布吉街道吉华路247号下水径商业大厦三层 3/f'
district '龙岗区'
city '深圳市'
country '中国'
}
}
{
"conference": {
"name": "SZJUG",
"subject": "Groovy on Android",
"date": 2016,
"time": [
"13:00",
"16:00"
],
"address": {
"place": "GRAPE 联合创业空间",
"street": "布吉街道吉华路247号下水径商业大厦三层 3/f'",
"district": "龙岗区",
"city": "深圳市",
"country": "中国"
}
}
}
JSON
7) Immutability
@Immutable(copyWith = true)
class User {
String username, email
}
7) Immutability
// Create immutable instance of User.
def paul = new User('PaulVI', 'paul.verest@live.com')
// will throw an exception on
// paul.email = 'pupkin@mail.com'
def tomasz = mrhaki.copyWith(username: 'Tomasz')
8) String interpolation
def level = "badly"
println "I love SZJUG $level"
// Java
TextView view =
new TextView(context);
view.setText(name);
view.setTextSize(16f);
view.setTextColor(Color.WHITE);
TextView view =
new TextView(context)
view.with {
text = name
textSize = 16f
textColor = Color.WHITE
}
->
How to read text file from SD card?
def f = new FIle("/sdcard/dir/f.txt")
if (f.exists() && f.canRead()) {
view.text = f.text
}
You have to write a lot of anonymous classes EVERYWHERE
// Java
button.setOnClickListener(new View.OnClickListener() {
@Override
void onClick(View v) {
startActivity(intent);
}
})
button.onClickListener = { startActivity(intent) }
->
No native support for generating classes
at runtime
Focus on @CompileStatic
Problems
Generate bytecode, that runs
at the same speed as java files
How to start?
Gradle plugin
buildscript {
dependencies {
classpath 'com.android.tools.build:gradle:1.5.0'
classpath 'org.codehaus.groovy:gradle-groovy-android-plugin:0.3.10'
}
}
apply plugin: 'groovyx.grooid.groovy-android'
dependencies {
compile 'org.codehaus.groovy:groovy:2.4.6:grooid'
}
Performance
Groovy jar 4.5 MB
Application size 2 MB
ProGuard only 1 MB!
~8.2 MB of RAM
for @CompileStatic
if not - slower and more RAM
Frameworks
SwissKnife
http://arasthel.github.io/SwissKnife/
def "should display hello text"() {
given:
def textView = new TextView(RuntimeEnvironment.application)
expect:
textView.text == "Hello"
}
Familiar with that?
Spock
http://robospock.org/
?

Contenu connexe

En vedette

Metaprogramming with Groovy
Metaprogramming with GroovyMetaprogramming with Groovy
Metaprogramming with GroovyAli Tanwir
 
Groovy in the Cloud
Groovy in the CloudGroovy in the Cloud
Groovy in the CloudDaniel Woods
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvmArnaud Giuliani
 
Spring one 2012 Groovy as a weapon of maas PaaSification
Spring one 2012 Groovy as a weapon of maas PaaSificationSpring one 2012 Groovy as a weapon of maas PaaSification
Spring one 2012 Groovy as a weapon of maas PaaSificationNenad Bogojevic
 
We thought we were doing continuous delivery and then...
We thought we were doing continuous delivery and then... We thought we were doing continuous delivery and then...
We thought we were doing continuous delivery and then... Suzie Prince
 
Java collections the force awakens
Java collections  the force awakensJava collections  the force awakens
Java collections the force awakensRichardWarburton
 
Groovy for java developers
Groovy for java developersGroovy for java developers
Groovy for java developersPuneet Behl
 
Reactive Streams and the Wide World of Groovy
Reactive Streams and the Wide World of GroovyReactive Streams and the Wide World of Groovy
Reactive Streams and the Wide World of GroovySteve Pember
 
Be More Productive with Kotlin
Be More Productive with KotlinBe More Productive with Kotlin
Be More Productive with KotlinBrandon Wever
 
Building an Extensible, Resumable DSL on Top of Apache Groovy
Building an Extensible, Resumable DSL on Top of Apache GroovyBuilding an Extensible, Resumable DSL on Top of Apache Groovy
Building an Extensible, Resumable DSL on Top of Apache Groovyjgcloudbees
 
Java 8 and 9 in Anger
Java 8 and 9 in AngerJava 8 and 9 in Anger
Java 8 and 9 in AngerTrisha Gee
 
Kotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyKotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyMobileAcademy
 
Groovyscriptingformanualandautomationtestingusingrobotframework 141221014703-...
Groovyscriptingformanualandautomationtestingusingrobotframework 141221014703-...Groovyscriptingformanualandautomationtestingusingrobotframework 141221014703-...
Groovyscriptingformanualandautomationtestingusingrobotframework 141221014703-...Bhaskara Reddy Sannapureddy
 
Java 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useJava 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useSharon Rozinsky
 
Java 9 Functionality and Tooling
Java 9 Functionality and ToolingJava 9 Functionality and Tooling
Java 9 Functionality and ToolingTrisha Gee
 
Migrating to IntelliJ IDEA from Eclipse
Migrating to IntelliJ IDEA from EclipseMigrating to IntelliJ IDEA from Eclipse
Migrating to IntelliJ IDEA from EclipseTrisha Gee
 
Continuous integration and delivery for java based web applications
Continuous integration and delivery for java based web applicationsContinuous integration and delivery for java based web applications
Continuous integration and delivery for java based web applicationsSunil Dalal
 
Fabulous Tests on Spock and Groovy
Fabulous Tests on Spock and GroovyFabulous Tests on Spock and Groovy
Fabulous Tests on Spock and GroovyYaroslav Pernerovsky
 

En vedette (20)

Metaprogramming with Groovy
Metaprogramming with GroovyMetaprogramming with Groovy
Metaprogramming with Groovy
 
Groovy in the Cloud
Groovy in the CloudGroovy in the Cloud
Groovy in the Cloud
 
Ci for-android-apps
Ci for-android-appsCi for-android-apps
Ci for-android-apps
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvm
 
Spring one 2012 Groovy as a weapon of maas PaaSification
Spring one 2012 Groovy as a weapon of maas PaaSificationSpring one 2012 Groovy as a weapon of maas PaaSification
Spring one 2012 Groovy as a weapon of maas PaaSification
 
We thought we were doing continuous delivery and then...
We thought we were doing continuous delivery and then... We thought we were doing continuous delivery and then...
We thought we were doing continuous delivery and then...
 
Java collections the force awakens
Java collections  the force awakensJava collections  the force awakens
Java collections the force awakens
 
Groovy for java developers
Groovy for java developersGroovy for java developers
Groovy for java developers
 
Reactive Streams and the Wide World of Groovy
Reactive Streams and the Wide World of GroovyReactive Streams and the Wide World of Groovy
Reactive Streams and the Wide World of Groovy
 
Be More Productive with Kotlin
Be More Productive with KotlinBe More Productive with Kotlin
Be More Productive with Kotlin
 
Building an Extensible, Resumable DSL on Top of Apache Groovy
Building an Extensible, Resumable DSL on Top of Apache GroovyBuilding an Extensible, Resumable DSL on Top of Apache Groovy
Building an Extensible, Resumable DSL on Top of Apache Groovy
 
Java 8 and 9 in Anger
Java 8 and 9 in AngerJava 8 and 9 in Anger
Java 8 and 9 in Anger
 
Kotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyKotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRready
 
Groovyscriptingformanualandautomationtestingusingrobotframework 141221014703-...
Groovyscriptingformanualandautomationtestingusingrobotframework 141221014703-...Groovyscriptingformanualandautomationtestingusingrobotframework 141221014703-...
Groovyscriptingformanualandautomationtestingusingrobotframework 141221014703-...
 
Java 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useJava 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually use
 
Java 9 Functionality and Tooling
Java 9 Functionality and ToolingJava 9 Functionality and Tooling
Java 9 Functionality and Tooling
 
Migrating to IntelliJ IDEA from Eclipse
Migrating to IntelliJ IDEA from EclipseMigrating to IntelliJ IDEA from Eclipse
Migrating to IntelliJ IDEA from Eclipse
 
Continuous integration and delivery for java based web applications
Continuous integration and delivery for java based web applicationsContinuous integration and delivery for java based web applications
Continuous integration and delivery for java based web applications
 
Docker and java
Docker and javaDocker and java
Docker and java
 
Fabulous Tests on Spock and Groovy
Fabulous Tests on Spock and GroovyFabulous Tests on Spock and Groovy
Fabulous Tests on Spock and Groovy
 

Similaire à Groovy on Android

Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume LaforgeGroovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume LaforgeGuillaume Laforge
 
An Introduction to Groovy for Java Developers
An Introduction to Groovy for Java DevelopersAn Introduction to Groovy for Java Developers
An Introduction to Groovy for Java DevelopersKostas Saidis
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyDavid Padbury
 
GroovyFX - Groove JavaFX
GroovyFX - Groove JavaFXGroovyFX - Groove JavaFX
GroovyFX - Groove JavaFXsascha_klein
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Wsloffenauer
 
Gradle in 45min - JBCN2-16 version
Gradle in 45min - JBCN2-16 versionGradle in 45min - JBCN2-16 version
Gradle in 45min - JBCN2-16 versionSchalk Cronjé
 
Groovy And Grails Introduction
Groovy And Grails IntroductionGroovy And Grails Introduction
Groovy And Grails IntroductionEric Weimer
 
Infinum android talks_10_getting groovy on android
Infinum android talks_10_getting groovy on androidInfinum android talks_10_getting groovy on android
Infinum android talks_10_getting groovy on androidInfinum
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Guillaume Laforge
 
淺談 Groovy 與 AWS 雲端應用開發整合
淺談 Groovy 與 AWS 雲端應用開發整合淺談 Groovy 與 AWS 雲端應用開發整合
淺談 Groovy 與 AWS 雲端應用開發整合Kyle Lin
 
eXo EC - Groovy Programming Language
eXo EC - Groovy Programming LanguageeXo EC - Groovy Programming Language
eXo EC - Groovy Programming LanguageHoat Le
 
Javaone2008 Bof 5102 Groovybuilders
Javaone2008 Bof 5102 GroovybuildersJavaone2008 Bof 5102 Groovybuilders
Javaone2008 Bof 5102 GroovybuildersAndres Almiray
 
Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Guillaume Laforge
 
Groovy a Scripting Language for Java
Groovy a Scripting Language for JavaGroovy a Scripting Language for Java
Groovy a Scripting Language for JavaCharles Anderson
 
WebSocket JSON Hackday
WebSocket JSON HackdayWebSocket JSON Hackday
WebSocket JSON HackdaySomay Nakhal
 
Meetup#1: 10 reasons to fall in love with MongoDB
Meetup#1: 10 reasons to fall in love with MongoDBMeetup#1: 10 reasons to fall in love with MongoDB
Meetup#1: 10 reasons to fall in love with MongoDBMinsk MongoDB User Group
 
GroovyFX - groove JavaFX Gr8Conf EU 2017
GroovyFX - groove JavaFX Gr8Conf EU 2017GroovyFX - groove JavaFX Gr8Conf EU 2017
GroovyFX - groove JavaFX Gr8Conf EU 2017sascha_klein
 

Similaire à Groovy on Android (20)

Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume LaforgeGroovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
 
An Introduction to Groovy for Java Developers
An Introduction to Groovy for Java DevelopersAn Introduction to Groovy for Java Developers
An Introduction to Groovy for Java Developers
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
GroovyFX - Groove JavaFX
GroovyFX - Groove JavaFXGroovyFX - Groove JavaFX
GroovyFX - Groove JavaFX
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws
 
Gradle in 45min - JBCN2-16 version
Gradle in 45min - JBCN2-16 versionGradle in 45min - JBCN2-16 version
Gradle in 45min - JBCN2-16 version
 
Groovy And Grails Introduction
Groovy And Grails IntroductionGroovy And Grails Introduction
Groovy And Grails Introduction
 
Go react codelab
Go react codelabGo react codelab
Go react codelab
 
Infinum android talks_10_getting groovy on android
Infinum android talks_10_getting groovy on androidInfinum android talks_10_getting groovy on android
Infinum android talks_10_getting groovy on android
 
NodeJS
NodeJSNodeJS
NodeJS
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
 
淺談 Groovy 與 AWS 雲端應用開發整合
淺談 Groovy 與 AWS 雲端應用開發整合淺談 Groovy 與 AWS 雲端應用開發整合
淺談 Groovy 與 AWS 雲端應用開發整合
 
eXo EC - Groovy Programming Language
eXo EC - Groovy Programming LanguageeXo EC - Groovy Programming Language
eXo EC - Groovy Programming Language
 
Javaone2008 Bof 5102 Groovybuilders
Javaone2008 Bof 5102 GroovybuildersJavaone2008 Bof 5102 Groovybuilders
Javaone2008 Bof 5102 Groovybuilders
 
Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007
 
Groovy a Scripting Language for Java
Groovy a Scripting Language for JavaGroovy a Scripting Language for Java
Groovy a Scripting Language for Java
 
UIWebView Tips
UIWebView TipsUIWebView Tips
UIWebView Tips
 
WebSocket JSON Hackday
WebSocket JSON HackdayWebSocket JSON Hackday
WebSocket JSON Hackday
 
Meetup#1: 10 reasons to fall in love with MongoDB
Meetup#1: 10 reasons to fall in love with MongoDBMeetup#1: 10 reasons to fall in love with MongoDB
Meetup#1: 10 reasons to fall in love with MongoDB
 
GroovyFX - groove JavaFX Gr8Conf EU 2017
GroovyFX - groove JavaFX Gr8Conf EU 2017GroovyFX - groove JavaFX Gr8Conf EU 2017
GroovyFX - groove JavaFX Gr8Conf EU 2017
 

Dernier

sdfsadopkjpiosufoiasdoifjasldkjfl a asldkjflaskdjflkjsdsdf
sdfsadopkjpiosufoiasdoifjasldkjfl a asldkjflaskdjflkjsdsdfsdfsadopkjpiosufoiasdoifjasldkjfl a asldkjflaskdjflkjsdsdf
sdfsadopkjpiosufoiasdoifjasldkjfl a asldkjflaskdjflkjsdsdfJulia Kaye
 
Modelling Guide for Timber Structures - FPInnovations
Modelling Guide for Timber Structures - FPInnovationsModelling Guide for Timber Structures - FPInnovations
Modelling Guide for Timber Structures - FPInnovationsYusuf Yıldız
 
SATELITE COMMUNICATION UNIT 1 CEC352 REGULATION 2021 PPT BASICS OF SATELITE ....
SATELITE COMMUNICATION UNIT 1 CEC352 REGULATION 2021 PPT BASICS OF SATELITE ....SATELITE COMMUNICATION UNIT 1 CEC352 REGULATION 2021 PPT BASICS OF SATELITE ....
SATELITE COMMUNICATION UNIT 1 CEC352 REGULATION 2021 PPT BASICS OF SATELITE ....santhyamuthu1
 
Nodal seismic construction requirements.pptx
Nodal seismic construction requirements.pptxNodal seismic construction requirements.pptx
Nodal seismic construction requirements.pptxwendy cai
 
The relationship between iot and communication technology
The relationship between iot and communication technologyThe relationship between iot and communication technology
The relationship between iot and communication technologyabdulkadirmukarram03
 
How to Write a Good Scientific Paper.pdf
How to Write a Good Scientific Paper.pdfHow to Write a Good Scientific Paper.pdf
How to Write a Good Scientific Paper.pdfRedhwan Qasem Shaddad
 
Phase noise transfer functions.pptx
Phase noise transfer      functions.pptxPhase noise transfer      functions.pptx
Phase noise transfer functions.pptxSaiGouthamSunkara
 
cloud computing notes for anna university syllabus
cloud computing notes for anna university syllabuscloud computing notes for anna university syllabus
cloud computing notes for anna university syllabusViolet Violet
 
Landsman converter for power factor improvement
Landsman converter for power factor improvementLandsman converter for power factor improvement
Landsman converter for power factor improvementVijayMuni2
 
Power System electrical and electronics .pptx
Power System electrical and electronics .pptxPower System electrical and electronics .pptx
Power System electrical and electronics .pptxMUKULKUMAR210
 
Engineering Mechanics Chapter 5 Equilibrium of a Rigid Body
Engineering Mechanics  Chapter 5  Equilibrium of a Rigid BodyEngineering Mechanics  Chapter 5  Equilibrium of a Rigid Body
Engineering Mechanics Chapter 5 Equilibrium of a Rigid BodyAhmadHajasad2
 
ASME BPVC 2023 Section I para leer y entender
ASME BPVC 2023 Section I para leer y entenderASME BPVC 2023 Section I para leer y entender
ASME BPVC 2023 Section I para leer y entenderjuancarlos286641
 
Strategies of Urban Morphologyfor Improving Outdoor Thermal Comfort and Susta...
Strategies of Urban Morphologyfor Improving Outdoor Thermal Comfort and Susta...Strategies of Urban Morphologyfor Improving Outdoor Thermal Comfort and Susta...
Strategies of Urban Morphologyfor Improving Outdoor Thermal Comfort and Susta...amrabdallah9
 
Gender Bias in Engineer, Honors 203 Project
Gender Bias in Engineer, Honors 203 ProjectGender Bias in Engineer, Honors 203 Project
Gender Bias in Engineer, Honors 203 Projectreemakb03
 
A Seminar on Electric Vehicle Software Simulation
A Seminar on Electric Vehicle Software SimulationA Seminar on Electric Vehicle Software Simulation
A Seminar on Electric Vehicle Software SimulationMohsinKhanA
 
Design of Clutches and Brakes in Design of Machine Elements.pptx
Design of Clutches and Brakes in Design of Machine Elements.pptxDesign of Clutches and Brakes in Design of Machine Elements.pptx
Design of Clutches and Brakes in Design of Machine Elements.pptxYogeshKumarKJMIT
 
SUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docx
SUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docxSUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docx
SUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docxNaveenVerma126
 

Dernier (20)

sdfsadopkjpiosufoiasdoifjasldkjfl a asldkjflaskdjflkjsdsdf
sdfsadopkjpiosufoiasdoifjasldkjfl a asldkjflaskdjflkjsdsdfsdfsadopkjpiosufoiasdoifjasldkjfl a asldkjflaskdjflkjsdsdf
sdfsadopkjpiosufoiasdoifjasldkjfl a asldkjflaskdjflkjsdsdf
 
Modelling Guide for Timber Structures - FPInnovations
Modelling Guide for Timber Structures - FPInnovationsModelling Guide for Timber Structures - FPInnovations
Modelling Guide for Timber Structures - FPInnovations
 
SATELITE COMMUNICATION UNIT 1 CEC352 REGULATION 2021 PPT BASICS OF SATELITE ....
SATELITE COMMUNICATION UNIT 1 CEC352 REGULATION 2021 PPT BASICS OF SATELITE ....SATELITE COMMUNICATION UNIT 1 CEC352 REGULATION 2021 PPT BASICS OF SATELITE ....
SATELITE COMMUNICATION UNIT 1 CEC352 REGULATION 2021 PPT BASICS OF SATELITE ....
 
Nodal seismic construction requirements.pptx
Nodal seismic construction requirements.pptxNodal seismic construction requirements.pptx
Nodal seismic construction requirements.pptx
 
Litature Review: Research Paper work for Engineering
Litature Review: Research Paper work for EngineeringLitature Review: Research Paper work for Engineering
Litature Review: Research Paper work for Engineering
 
Présentation IIRB 2024 Marine Cordonnier.pdf
Présentation IIRB 2024 Marine Cordonnier.pdfPrésentation IIRB 2024 Marine Cordonnier.pdf
Présentation IIRB 2024 Marine Cordonnier.pdf
 
The relationship between iot and communication technology
The relationship between iot and communication technologyThe relationship between iot and communication technology
The relationship between iot and communication technology
 
How to Write a Good Scientific Paper.pdf
How to Write a Good Scientific Paper.pdfHow to Write a Good Scientific Paper.pdf
How to Write a Good Scientific Paper.pdf
 
Phase noise transfer functions.pptx
Phase noise transfer      functions.pptxPhase noise transfer      functions.pptx
Phase noise transfer functions.pptx
 
cloud computing notes for anna university syllabus
cloud computing notes for anna university syllabuscloud computing notes for anna university syllabus
cloud computing notes for anna university syllabus
 
Landsman converter for power factor improvement
Landsman converter for power factor improvementLandsman converter for power factor improvement
Landsman converter for power factor improvement
 
Power System electrical and electronics .pptx
Power System electrical and electronics .pptxPower System electrical and electronics .pptx
Power System electrical and electronics .pptx
 
Engineering Mechanics Chapter 5 Equilibrium of a Rigid Body
Engineering Mechanics  Chapter 5  Equilibrium of a Rigid BodyEngineering Mechanics  Chapter 5  Equilibrium of a Rigid Body
Engineering Mechanics Chapter 5 Equilibrium of a Rigid Body
 
ASME BPVC 2023 Section I para leer y entender
ASME BPVC 2023 Section I para leer y entenderASME BPVC 2023 Section I para leer y entender
ASME BPVC 2023 Section I para leer y entender
 
Strategies of Urban Morphologyfor Improving Outdoor Thermal Comfort and Susta...
Strategies of Urban Morphologyfor Improving Outdoor Thermal Comfort and Susta...Strategies of Urban Morphologyfor Improving Outdoor Thermal Comfort and Susta...
Strategies of Urban Morphologyfor Improving Outdoor Thermal Comfort and Susta...
 
Gender Bias in Engineer, Honors 203 Project
Gender Bias in Engineer, Honors 203 ProjectGender Bias in Engineer, Honors 203 Project
Gender Bias in Engineer, Honors 203 Project
 
A Seminar on Electric Vehicle Software Simulation
A Seminar on Electric Vehicle Software SimulationA Seminar on Electric Vehicle Software Simulation
A Seminar on Electric Vehicle Software Simulation
 
Design of Clutches and Brakes in Design of Machine Elements.pptx
Design of Clutches and Brakes in Design of Machine Elements.pptxDesign of Clutches and Brakes in Design of Machine Elements.pptx
Design of Clutches and Brakes in Design of Machine Elements.pptx
 
Lecture 2 .pdf
Lecture 2                           .pdfLecture 2                           .pdf
Lecture 2 .pdf
 
SUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docx
SUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docxSUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docx
SUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docx
 

Groovy on Android

  • 3. def speaker = new SZJUG.Speaker( name: 'Alexey Zhokhov', employer: 'Scentbird', occupation: 'Grails Developer', github: 'donbeave', email: 'alexey@zhokhov.com', site: 'http://www.zhokhov.com', description: """whole-stack engineer (back-end, front-end, mobile, UI/UX)""" )
  • 5. Groovy is inside the Gradle You probably know Groovy through Gradle already. Groovy is a superset of Java. It contains lots of cool stuff that makes Java fun!
  • 6. So, Why can Groovy be Android' Swift?
  • 7. Android N supports Java 8 "Android is in the Java stone age state" But not released
  • 9. Java on Android is very verbose
  • 10. public class FeedActivity { TextView mTextView; void updateFeed() { new FeedTask().execute("http://path/to/feed"); } class FeedTask extends AsyncTask<String, Void, String> { protected String doInBackground(String... params) { DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams()); HttpPost httppost = new HttpPost(params[0]); InputStream inputStream = null; String result = null; 1/4
  • 11. try { HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); inputStream = entity.getContent(); // json is UTF-8 by default BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line).append("n"); } result = sb.toString(); } catch (Exception e) { // Oops 2/4
  • 12. } finally { try { if (inputStream != null) { inputStream.close(); } } catch (Exception squish) { } } StringBuilder speakers = null; try { JSONObject jObject = new JSONObject(result); JSONArray jArray = jObject.getJSONArray("speakers"); speakers = new StringBuilder(); for (int i = 0; i < jArray.length(); i++) { speakers.append(jArray.getString(i)); speakers.append(" "); } 3/4
  • 13. } catch (JSONException e) { // do something? } return speakers.toString(); } @Override protected void onPostExecute(String s) { mTextView.setText(s); } } } 4/4
  • 14. So now, let’s see the equivalent in Groovy (no kidding either)
  • 15. class FeedActivity { TextView mTextView void updateFeed() { Fluent.async { def json = new JsonSlurper().parse([:], new URL('http://path/to/feed'), 'utf-8') json.speakers.join(' ') } then { mTextView.text = it } } }
  • 16. Because I'm lazy, I don't like to write a lot of code. And Groovy helps me with that.
  • 17. It's not only for writing less code, it's also for cool features and good readability. very consice language, actually
  • 20. 1) Groovy truth // if (s != null && s.length() > 0) { ...} if (s) { ... } // easy check for empty maps, list, empty strings
  • 21. 2) Elvis def name = person.name ?: "unknown"
  • 23. Where I have seen it?
  • 24. Right, Apple's Swift language was inspired by Groovy
  • 25. 4) List, maps (Groovy) def shoppingList = ["catfish", "water", "tulips", "blue paint"] shoppingList[1] = "bottle of water" def occupations = [ "Malcolm": "Captain", "Kaylee": "Mechanic", ] occupations["Jayne"] = "Public Relations" def emptyMap = [:] def emptyList = []
  • 26. 4) List, maps (Swift) var shoppingList = ["catfish", "water", "tulips", "blue paint"] shoppingList[1] = "bottle of water" var occupations = [ "Malcolm": "Captain", "Kaylee": "Mechanic", ] occupations["Jayne"] = "Public Relations" var emptyMap = [:] var emptyList = []
  • 27. 5) Named parameters (Groovy) def triangleAndSquare = new TriangleAndSquare(size: 10, name: "another test shape")
  • 28. 5) Named parameters (Swift) var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape")
  • 29. 6) @Lazy annotation (Groovy) class DataManager { @Lazy importer = new DataImporter() }
  • 30. 6) @Lazy annotation (Swift) class DataManager { @lazy var importer = DataImporter() }
  • 31. 7) Closure (Groovy) numbers.collect { int number -> def result = 3 * numbers return result }
  • 32. 7) Closure (Swift) numbers.map({ (number: Int) -> Int in let result = 3 * number return result })
  • 33. What else is cool in Groovy?
  • 34. 8) Builders import groovy.json.* def json = new JsonBuilder() json.conference { name 'SZJUG' subject 'Groovy on Android' date 2016 time ['13:00', '16:00'] address { place 'GRAPE 联合创业空间' street '布吉街道吉华路247号下水径商业大厦三层 3/f' district '龙岗区' city '深圳市' country '中国' } }
  • 35. { "conference": { "name": "SZJUG", "subject": "Groovy on Android", "date": 2016, "time": [ "13:00", "16:00" ], "address": { "place": "GRAPE 联合创业空间", "street": "布吉街道吉华路247号下水径商业大厦三层 3/f'", "district": "龙岗区", "city": "深圳市", "country": "中国" } } } JSON
  • 36. 7) Immutability @Immutable(copyWith = true) class User { String username, email }
  • 37. 7) Immutability // Create immutable instance of User. def paul = new User('PaulVI', 'paul.verest@live.com') // will throw an exception on // paul.email = 'pupkin@mail.com' def tomasz = mrhaki.copyWith(username: 'Tomasz')
  • 38. 8) String interpolation def level = "badly" println "I love SZJUG $level"
  • 39. // Java TextView view = new TextView(context); view.setText(name); view.setTextSize(16f); view.setTextColor(Color.WHITE); TextView view = new TextView(context) view.with { text = name textSize = 16f textColor = Color.WHITE } ->
  • 40. How to read text file from SD card? def f = new FIle("/sdcard/dir/f.txt") if (f.exists() && f.canRead()) { view.text = f.text }
  • 41. You have to write a lot of anonymous classes EVERYWHERE // Java button.setOnClickListener(new View.OnClickListener() { @Override void onClick(View v) { startActivity(intent); } }) button.onClickListener = { startActivity(intent) } ->
  • 42. No native support for generating classes at runtime Focus on @CompileStatic Problems Generate bytecode, that runs at the same speed as java files
  • 44. Gradle plugin buildscript { dependencies { classpath 'com.android.tools.build:gradle:1.5.0' classpath 'org.codehaus.groovy:gradle-groovy-android-plugin:0.3.10' } } apply plugin: 'groovyx.grooid.groovy-android' dependencies { compile 'org.codehaus.groovy:groovy:2.4.6:grooid' }
  • 46. Groovy jar 4.5 MB Application size 2 MB ProGuard only 1 MB! ~8.2 MB of RAM for @CompileStatic if not - slower and more RAM
  • 49. def "should display hello text"() { given: def textView = new TextView(RuntimeEnvironment.application) expect: textView.text == "Hello" } Familiar with that?
  • 51. ?