Top Banner
51

Groovy on Android

Apr 12, 2017

Download

Engineering

Alexey Zhokhov
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Groovy on Android
Page 2: Groovy on Android

Who are you?

Page 3: Groovy on Android

def speaker = new SZJUG.Speaker(name: 'Alexey Zhokhov', employer: 'Scentbird', occupation: 'Grails Developer', github: 'donbeave', email: '[email protected]', site: 'http://www.zhokhov.com',description: """whole-stack

engineer(back-end, front-end, mobile, UI/UX)""")

Page 4: Groovy on Android

Android on Gradle

Page 5: Groovy on Android

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!

Page 6: Groovy on Android

So, Why can Groovy be Android' Swift?

Page 7: Groovy on Android

Android N supports Java 8

"Android is in the Java stone age state"

But not released

Page 8: Groovy on Android

Multi-faceted language:Object-orientedDynamicFunctionalStatic

Groovy is

Straightforward integration with Java.

Page 9: Groovy on Android

Java on Android is very verbose

Page 10: Groovy on Android

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

Page 11: Groovy on Android

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

Page 12: Groovy on Android

} 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

Page 13: Groovy on Android

} catch (JSONException e) { // do something? } return speakers.toString(); } @Override protected void onPostExecute(String s) { mTextView.setText(s); } }}

4/4

Page 14: Groovy on Android

So now, let’s see the equivalent in Groovy

(no kidding either)

Page 15: Groovy on Android

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 } }}

Page 16: Groovy on Android

Because I'm lazy, I don't like to write a lot of code.

And Groovy helps me with that.

Page 17: Groovy on Android

It's not only for writing less code,

it's also for cool features and good readability.

very consice language, actually

Page 18: Groovy on Android

SemicolonsParenthesisreturn keywordpublic keyword

Optional

Page 19: Groovy on Android

Sugar syntax

Page 20: Groovy on Android

1) Groovy truth

// if (s != null && s.length() > 0) { ...}

if (s) { ... }// easy check for empty maps, list, empty strings

Page 21: Groovy on Android

2) Elvis

def name = person.name ?: "unknown"

Page 22: Groovy on Android

3) Save navigation

order?.lineItem?.item?.name

Page 23: Groovy on Android

Where I have seen it?

Page 24: Groovy on Android

Right, Apple's Swift language was inspired by Groovy

Page 25: Groovy on Android

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 = []

Page 26: Groovy on Android

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 = []

Page 27: Groovy on Android

5) Named parameters (Groovy)

def triangleAndSquare = new TriangleAndSquare(size: 10, name: "another test shape")

Page 28: Groovy on Android

5) Named parameters (Swift)

var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape")

Page 29: Groovy on Android

6) @Lazy annotation (Groovy)

class DataManager { @Lazy importer = new DataImporter()}

Page 30: Groovy on Android

6) @Lazy annotation (Swift)

class DataManager { @lazy var importer = DataImporter()}

Page 31: Groovy on Android

7) Closure (Groovy)

numbers.collect { int number -> def result = 3 * numbers return result}

Page 32: Groovy on Android

7) Closure (Swift)

numbers.map({ (number: Int) -> Int in let result = 3 * number return result})

Page 33: Groovy on Android

What else is cool in Groovy?

Page 34: Groovy on Android

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 ' 中国 ' }}

Page 35: Groovy on Android

->{ "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

Page 36: Groovy on Android

7) Immutability

@Immutable(copyWith = true)class User { String username, email}

Page 37: Groovy on Android

7) Immutability

// Create immutable instance of User.def paul = new User('PaulVI', '[email protected]') // will throw an exception on// paul.email = '[email protected]' def tomasz = mrhaki.copyWith(username: 'Tomasz')

Page 38: Groovy on Android

8) String interpolation

def level = "badly" println "I love SZJUG $level"

Page 39: Groovy on Android

// JavaTextView 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}

->

Page 40: Groovy on Android

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}

Page 41: Groovy on Android

You have to write a lot of anonymous classes EVERYWHERE// Javabutton.setOnClickListener(new View.OnClickListener() { @Override void onClick(View v) { startActivity(intent); }})

button.onClickListener = { startActivity(intent) }->

Page 42: Groovy on Android

No native support for generating classes at runtime

Focus on @CompileStatic

Problems

Generate bytecode, that runs at the same speed as java files

Page 43: Groovy on Android

How to start?

Page 44: Groovy on Android

Gradle pluginbuildscript { 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'}

Page 45: Groovy on Android

Performance

Page 46: Groovy on Android

Groovy jar 4.5 MBApplication size 2 MBProGuard only 1 MB! ~8.2 MB of RAM for @CompileStatic if not - slower and more RAM

Page 47: Groovy on Android

Frameworks

Page 48: Groovy on Android

SwissKnife http://arasthel.github.io/SwissKnife/

Page 49: Groovy on Android

def "should display hello text"() { given: def textView = new TextView(RuntimeEnvironment.application) expect: textView.text == "Hello"}

Familiar with that?

Page 50: Groovy on Android

Spockhttp://robospock.org/

Page 51: Groovy on Android

?