inaka

Latest blog entries

/
The Art of Writing a Blogpost

The Art of Writing a Blogpost

Apr 11 2017 : Matias Vera

/
SpellingCI: No more spelling mistakes in your markdown flies!

Feb 14 2017 : Felipe Ripoll

/
Fast reverse geocoding with offline-geocoder

Do you need a blazing fast reverse geocoder? Enter offline-geocoder!

Jan 18 2017 : Roberto Romero

/
Using Jayme to connect to the new MongooseIM REST services

MongooseIM has RESTful services!! Here I show how you can use them in an iOS application.

Dec 13 2016 : Sergio Abraham

/
20 Questions, or Maybe a Few More

20 Questions, or Maybe a Few More

Nov 16 2016 : Stephanie Goldner

/
The Power of Meeting People

Because conferences and meetups are not just about the technical stuff.

Nov 01 2016 : Pablo Villar

/
Finding the right partner for your app build

Sharing some light on how it is to partner with us.

Oct 27 2016 : Inaka

/
Just Play my Sound

How to easily play a sound in Android

Oct 25 2016 : Giaquinta Emiliano

/
Opening our Guidelines to the World

We're publishing our work guidelines for the world to see.

Oct 13 2016 : Brujo Benavides

/
Using NIFs: the easy way

Using niffy to simplify working with NIFs on Erlang

Oct 05 2016 : Hernan Rivas Acosta

/
Function Naming In Swift 3

How to write clear function signatures, yet expressive, while following Swift 3 API design guidelines.

Sep 16 2016 : Pablo Villar

/
Jenkins automated tests for Rails

How to automatically trigger rails tests with a Jenkins job

Sep 14 2016 : Demian Sciessere

/
Erlang REST Server Stack

A description of our usual stack for building REST servers in Erlang

Sep 06 2016 : Brujo Benavides

/
Replacing JSON when talking to Erlang

Using Erlang's External Term Format

Aug 17 2016 : Hernan Rivas Acosta

/
Gadget + Lewis = Android Lint CI

Integrating our Android linter with Github's pull requests

Aug 04 2016 : Fernando Ramirez and Euen Lopez

/
Passwordless login with phoenix

Introducing how to implement passwordless login with phoenix framework

Jul 27 2016 : Thiago Borges

/
Beam Olympics

Our newest game to test your Beam Skills

Jul 14 2016 : Brujo Benavides

/
Otec

Three Open Source Projects, one App

Jun 28 2016 : Andrés Gerace

/
CredoCI

Running credo checks for elixir code on your github pull requests

Jun 16 2016 : Alejandro Mataloni

/
Thoughts on rebar3

Thoughts on rebar3

Jun 08 2016 : Hernán Rivas Acosta

/
See all Inaka's blog posts >>

/
Android development with Kotlin

Fernando Ramirez wrote this on January 15, 2016 under android, dev, functional, gradle, inaka, kotlin, language .

What is Kotlin?

Kotlin is a statically typed programming language for the Java Virtual Machine, Android and web browsers. Inside Android apps we can use Kotlin language to replace Java code, but also we can use both together having Java classes and Kotlin classes in the same project.

Getting started

Using Android Studio

1. Install the Kotlin plugin

Go to "Android Studio" menu, "Preferences", "Plugins", search 'Kotlin' and install the plugin. Then you will have to restart Android Studio.

2. Start a new Android project

Let's create a new Android project: go to "Start a new Android Studio project" or "File" menu, and click "New project".

3. Configure gradle

You can configure Kotlin in the project by clicking "Help" on the menu, then "Find Action" (or press ⇧⌘A) and finally enter "Configure Kotlin in Project". Then you should choose the Kotlin version that you want. After that, the app/build.gradle file should be updated. Also, instead of using "Find Action", you can edit the app/build.gradle file manually. Here is an example:

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "examples.kotlin.inaka.com"
        minSdkVersion 17
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }
}

buildscript {
    ext.kotlin_version = '1.0.0-beta-4583'
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
    }
}

repositories {
    mavenCentral()
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}

4. Convert .java to Kotlin (.kt) files

Open a Java file and choose "Help" on the menu, then "Find Action" (or press ⇧⌘A) and enter the action "Convert Java File to Kotlin File". Alternatively you can call this option via "Code" menu, "Convert Java File to Kotlin File".

Some characteristics

Using Kotlin to develop Android apps introduce many differences and 'advantages' compared to Java development. Here I will mention some of them:

Variables and type inference

var age = 5 // you don't need to declare as an Int

But if you want to declare the type:

var age: Int = 5

Java's 'final' = Kotlin's 'val':

val name = "Fernando" // 'val' can't be reassigned

Pattern matching

fun valueDependingOnType(type: Int) {
    var value = 0
    when (type) {
        1 -> toast(value.toString())
        2 -> {
            value = 100
            toast(value.toString())
        }
        else -> toast(type.toString())
    }
}

Safe call - null verification

Verifying null object with Java:

int len;
if(list != null){
  len = list.size();
}

Same as above but using Kotlin language:

var len = list?.size

Safe cast example:

val x: String? = y as? String

Properties

Avoid usage of getters and setters:

var user = User()
user.name = "Fernando" // set user's name
toast(user.name)       // get user's name

Companion object

A Kotlin class can have a companion object. This is like the static variable for Java classes. For example:

class MainActivity : AppCompatActivity() {

  companion object {
      val PICK_CONTACT = 100
  }

  ...
}

Then you can call MainActivity.PICK_CONTACT and it will receive the value 100.

String templates

fun printFirst(array: Array<String>) { 
  if (array.size == 0) return 
  print("First value: ${array[0]}") 
}

Ranges

if (x in 1..y)
print("x is  >= 1 and <= y")

Lambda expressions

fun foo(numbers: ArrayList<Int>) { 
   val doubled = numbers.map { elem -> elem * 2 } 
   ...
}

or

fun foo(numbers: ArrayList<Int>) { 
   val doubled = numbers.map { it * 2 } 
   ...
}

Kotlin extensions - finding views

You don't need to call the findViewById() method. For example, if you want to change programatically the text of a TextView with id "textView1" from activity_main.xml you can do:

import kotlinx.android.synthetic.main.activity_main.*

And then into onCreate method:

textView1.text = "example text"

Resources

Kotlin language oficial documentation

Some open source example projects

  • kotlillon Compilation of simple Kotlin examples, all together in one Android app
  • restful_android_kotlin Restful Android app example, using Kotlin with Realm, Retrofit, Picasso, Robospice and more

Some interesting Kotlin libraries for Android development