Developing Android Apps with Scala




Jim Fulton, Zope Corporation

DC Droids/Riak DC Meetup, August 8, 2013

http://jimfulton.info/talks/scala-android.html (http://zo.pe/bHWC)

Who are we?

Java

Scala

Type inference means fewer declarations

Java:

Pattern emailPattern = Pattern.compile("[^\\s@]+@[^\\s@]+\\.[^\\s@]+$");
EditText emailField = (EditText) findViewById(R.id.email_entry_field);
String emailAddress = emailField.getText();
if (! emailPattern.matcher(emailAddress).matches()) {
   ...

Scala:

val emailPattern = "[^\\s@]+@[^\\s@]+\\.[^\\s@]+$".r
val emailField = findViewById(R.id.email_entry_field).asInstanceOf[EditText]
val emailAddress = emailField.getText
if (emailPattern.findFirstIn(emailField).isEmpty) {
  ...

functions, collections

Java:

protected void enrollCustomer(String email, String orgId, String id) {
    RequestParams params = new RequestParams();
    params.put("email", email);
    if (id != null)
        params.put("id", id);
    App.xhr.post("orgs/" + orgId + "/customers", params,
            new FriendlyHttpResponseHandler(getApplicationContext()) {
                @Override
                public void onSuccess(JSONObject resp) {
                    lookupCustomer();
                }
            }); }

Scala:

def enrollCustomer(email: String, orgId: String, id: String) {
  App.xhr.post("orgs/" + orgId + "/customers",
               Map("email" -> email) ++
                 (if (id == null) Nil else Map("id" -> id))) {
    resp => lookupCustomer()
  } }

Unchecked exceptions

Java:

try {
    org = new JSONObject(getIntent().getExtras().getString("org"));
    orgId = org.getString("id");
} catch (JSONException e) {
    e.printStackTrace();
}

Scala:

org = new JSONObject(getIntent.getExtras.getString("org"))
orgId = org.getString("id")

Implicit conversions

Allows extension of standard Java types, API bridging.

Pixels:

32 dip

String to URL:

openUri("http://scaloid.org")

Resource ids to char sequences:

toast(R.string.my_message)

JSON array to iterable:

val offers = for(
  offer <- json.toJSONArray(json.names())
  ) yield new Offer(offer)

Who's using Scala for Android

Scala build challenges

Android build process

It hurts us!

ADT (old) + Scala

Don't do this, but we did. :)

SBT

Simple (ha!) Scala Built Tool

SBT Android plugin

Modes:

Getting started

http://fxthomas.github.io/android-plugin/

brew install giter8
g8 jimfulton/android-app

Status

IntelliJ

Scaloid

https://github.com/pocorall/scaloid

Tools/Issues for Android Development

Questions

http://jimfulton.info/talks/scala-android.html (http://zo.pe/bHWC)

http://fxthomas.github.io/android-plugin/

http://groups.google.com/group/scala-on-android

IRC: #sbt-android on Freenode

https://github.com/pocorall/scaloid