1 of 12

Kotlin, a Year on

Mike Gouline

gouline.net | @mikestruct

2 of 12

What has changed?

  • New features
  • Improved interoperability
  • Better documentation
    • Example code
    • Complete tutorials
  • Community exposure
    • Books published
    • Libraries written
    • Developer articles

3 of 12

Annotation processing (kapt)

  • Dagger 2 works!
  • Effortless
    • Latest Kotlin plugin for Gradle
    • Usual Dagger 2 dependencies
  • Fine print
    • Dagger builder must be used in Java
  • Related
    • Late-init properties

4 of 12

Anko

  • Programmatic layouts
  • Why would you?
    • DSL instead of XML
    • Compact and readable
    • IDE integration with previews
  • Why wouldn’t you?
    • Nothing wrong with XML layouts
    • No support for screen-based variants

5 of 12

Anko: Example

verticalLayout {

padding = dip(16)

textView("Username:") {

textSize = 18f

}.layoutParams { verticalMargin = dip(4) }

val login = editText()

button("Sign up") {

textSize = 20f

onClick { login(login.text) }

}.layoutParams { topMargin = dip(8) }

}

6 of 12

Anko: Example

7 of 12

Android extensions

  • Butter Knife not supported; who needs it?
  • No need for (explicit) instance variables
  • How?
    • Import synthetic layout
      • import kotlinx.android.synthetic.<layout>.*
    • Just use views by ID
      • e.g. this.txt_status.setText(“OK”);
    • Synthetic calls are replaced by functional calls

8 of 12

Android extensions: Example

<TextView

android:id="@+id/hello"

android:layout_width="fill_parent"

android:layout_height="wrap_content"/>

import kotlinx.android.synthetic.main.*

public class MyActivity : Activity() {

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

setContentView(R.layout.main)

this.hello.setText("Hi!")

}

}

9 of 12

Nullability

  • Remember nullable types? e.g. String?
  • Annoyance
    • Objects not created in your Kotlin class must be nullable, even if guaranteed to never be null
  • Solutions
    • @NonNull and @Nullable annotations
      • Now honoured in Java interop
    • Late-init properties
      • Injected values no longer have to be nullable
      • e.g. @Inject lateinit val foo: Foo

10 of 12

Sealed classes

sealed class Pet(val name: String) {

class Dog(name: String): Pet(name)

class Cat(name: String): Pet(name)

}

fun Pet.saySomething(): String {

return when (this) {

is Dog -> "woof"

is Cat -> "meow"

}

}

  • Algebraic Data Types (ADTs)

11 of 12

Miscellaneous

  • JUnit support for Android
  • Secondary constructors
    • In addition to the class signature
  • Annotation syntax
    • [Inject] became @Inject
  • Companion objects
    • Replacing “class objects” for static members
  • Lazy evaluations
    • Delayed evaluation of variable definition
  • Filling properties from a map
    • Creating properties (getter/setter) from a map

12 of 12

Thank you!

gouline.net | @mikestruct