Kotlin intro

Anton Rutkevich

JunoLab

About me

  • Android
  • Java, Kotlin, Groovy
  • Gradle, mobile CI

Who's out there? :)

Why Kotlin?

We need
safe & readable
code

Kotlin

  • Created by JetBrains
  • Announced in 2011
  • Version - M13 (as of Sep 2015)
  • Not 1.0 yet

Easy to write safe code

Kotlin language
Libraries

Kotlin language

General

val / var, not null

// Constant
val a: Int = 1

// Variable
var b: Int = 2
b++

// Nullable variable
var c: String? = null
c?.charAt(0) // returns Char?

Functions

( Demo 1 )

When

fun cases(obj: Any) {
    when (obj) {
        1          -> print("One")
        "Hello"    -> print("Greeting")
        is Long    -> print("Long")
        !is String -> print("Not a string")
        else       -> print("Unknown")
    }
}

Return if / when / try

fun textColorRes(): Int {
    return if (isValid()) {
        R.color.green
    } else {
        R.color.red
    }
}

Kotlin language

Classes

Constructors

class Cat

class Dog(val name: String)

class Mouse(name: String) {
    init {
        logger.info("Initialized with ${name}")
    }
}

Constructors 2

class MyView : View {
    constructor(ctx: Context) : super(ctx) {
    }

    constructor(ctx: Context, attrs: AttributeSet) 
       : super(ctx, attrs) {
    }
}

Properties

class Address { 
  var city: String = // ...
  
  var street: String
    get() = {
      // ...
    }
    set(value) {
      // ...
    }
}

Data classes

( Demo 2 )

Inheritance

open class Base {
    open fun canBeOverridden() {}
    fun notOverrideable() {}
}

class Derived() : Base() {
    override fun canBeOverridden() {}
}

Nested & Inner classes

class Outer {
  val bar = 1
  class Nested {
    // has no access to 'bar'
  }
}

class Outer {
  var bar = 1
  inner class Inner {
    // can access 'bar'
  }
}

Delegates

class MyActivity: Activity() {

    var loginButton: Button by Delegates.notNull()

    val userNameLabel: TextView by Delegates.lazy {
        findViewById(R.id.user_name_label) as TextView
    }

    var userName: String by Delegates.observable("") { 
            metadata, old, new ->
        userNameLabel.setText(new)
    }
}

Extensions

fun Context.shortToast(text: String) {
    Toast.makeText(this, text, Toast.LENGTH_SHORT)
         .show()
}

class MainActivity: Activity() {
    override fun onStart() {
        super.onStart()
        shortToast("On Start")
    }
}

Fighting nulls!

( Demo 3 )

Kotlin language

Lambdas & Collections

Lambdas

class MainActivity: Activity(), SomeCallbackListener {
    var loginButton: Button = ...

    override fun onCreate(savedInstanceState: Bundle) {
        loginButton.setOnClickListener { 
            // do something
        }
    }

    override fun onJobDone(result: String) {
        runOnUiThread {
            // Modify UI on main thread
        }
    }
}

Collections

val list: List<String> = listOf("1", "2", "3")
list.add("4") // No such method :)


val mutableList: MutableList<String> 
    = listOf("4", "5", "6")

mutableList.add("7") // OK

Collections + lambdas !

val list = listOf("one", "two", "three")

list.filter { 
    it.length() < 5 
}.map { 
    it.reverse() 
}.forEach { 
    Log.d(TAG, "String: ${it}") 
}

Libraries

Must make code easier to

write

read

test

and safer!

We use

RxJava

Dagger 2

Retrofit

Gson

and others

Rule of thumb

Regular* Java libraries work well with Kotlin

* regular: no APT, reflection,
other "black magic"

Watch out for nulls!

// non-null
val list = ArrayList<String>()
list.add(null) // allowed



// allowed, will throw an exception

val item = list.get(0).substring(1)
// non-null
val list = ArrayList<String>()
list.add(null) // allowed
val list: MutableList<String> = ArrayList()
list.add("Item") // null is rejected at compile time

// allowed, will throw an exception
// will never throw NPE
val item = list.get(0).substring(1)
            
            
            

YouTube:

Andrey Breslav - Flexible Types in Kotlin

M12

RxJava
is awesome!

( Demo 4 )

Dagger 2

Works, but with DI code in Java

Retrofit

just works :)

Gson, make it safe!

( Demo 5 )

Statistics

Shut up and take my money method count*

Library Size Method count
scala-library-2.11.7 5.7 Mb 50811
groovy-2.4.4 4.6 Mb 28768
kotlin-runtime-0.13.1513 294 Kb 1067
kotlin-stdlib-0.13.1513 878 Kb 7672

Project statistics

Avg. lines / file 63.5
Avg. SLOC / file 50
Largest file, lines 360

Fun stories

Upgrade

from M11 to M12

M12 to M13

will be a bit harder

Build.VERSION_CODES

Future of

Kotlin

Question? 

Anton Rutkevich,

JunoLab

@AntonRutkevich

+AntonRutkevich

anton.rutkevich

  • http://kotlinlang.org
  • Google "Kotlin Koans" - nice Kotlin exercises
  • YouTube "Andrey Breslav - Flexible Types in Kotlin"
  • https://slides.com/antonrutkevich/kotlin-intro-voxxed

Kotlin intro

By Anton Rutkevich

Kotlin intro

Kotlin intro for Voxxed conference, Vilnius

  • 1,600