Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Kotlin for Android apps programming

Kotlin for Android apps programming

Barcamp Bangkhen 5

Manatsawin Hanmongkolchai

November 16, 2014
Tweet

More Decks by Manatsawin Hanmongkolchai

Other Decks in Programming

Transcript

  1. Break label Java: for(..){ boolean flag=false; for(...){ flag=true; break; }

    if(flag){ break; } } Kotlin: @loop for(..){ for(..){ break@loop; } }
  2. No more getter & setter var stringRepresentation : String get()

    = this.toString() set(value) { setDataFromString(value) }
  3. Data class! data class User(val name: String, val age: Int)

    - equals - toString → User(name=a, age=1) - component1() = user.name - copy()
  4. Multiple inheritance with traits trait MyTrait { // must be

    stateless fun bar() // abstract fun foo() {} } class Child : MyTrait{ fun bar(){} } • Trait attributes can be overridden • Trait can access class' attribute without declaring it in trait itself
  5. Named argument fun printSpace(text : String, spcBefore : Int =

    0, spcAfter : Int = 0) { // ... } printSpace("hello world", spcAfter=5)
  6. Ruby-style function fun double(x : Int) : Int = x

    * 2 fun double(x : Int) = x * 2
  7. Anonymous function (findViewById(R.id.button) as Button). setOnClickListener({ // argument is implicitly

    defined as it }) (findViewById(R.id.button) as Button). setOnClickListener { event -> // ... }
  8. Null safety • var x : Int = 5 •

    Cannot be null • var y : Int? • Can be null
  9. Null safety • x methods cannot return NPE • y

    methods can return NPE ◦ Does not compile!
  10. Null safety • y?.length() ◦ Return y.length() or null if

    y is null • y?.length() ?: -1 ◦ Return y.length() or -1 if y is null • y!!.length() ◦ Return y.length() or NPE
  11. Null safety • if(y != null){ print(y) } • Compiler

    keep track of null check • var z = y as? Double ◦ z = (Double) y if y instanceof Double ◦ z = null if !(y instanceof Double)
  12. Null safety • if(y != null){ print(y) } • Compiler

    keep track of null check • var z = y as? Double ◦ z = (Double) y if y instanceof Double ◦ z = null if !(y instanceof Double)
  13. Extension fun JSONArray.toArrayList() : ArrayList<Object> = Array<Object>(length(), {i -> get(i)})

    val x = JSONArray(input) val y = x.toArrayList() Anonymous Function
  14. Android • Kotlin interoperates well with Java ◦ Java can

    call Kotlin stuff (may have magic name added) ◦ Kotlin can call Java stuff (non-primitive data type are platform type -- as safe as in Java) • Runtime size 884kB (ProGuard remove most of this) • Install as Android Studio plugin ◦ Automatically configure gradle
  15. Sample App https://github. com/whs/IUPEat • See initial commit for Java

    version • Should be the language of choice for next KUSmartBus (if I get to write one)
  16. Q&A