Slide 1

Slide 1 text

Kotlin Statically typed, modern language for industry Not swift of Android [email protected]

Slide 2

Slide 2 text

Agenda • Overview • Kotlin Basics • Work with Android • Adoption • Resources • Testing

Slide 3

Slide 3 text

Kotlin • Build and used by JetBrain • Since 2010, • 1.0 -Beta 2 • Tooling support • Very low learning curve

Slide 4

Slide 4 text

Statically typed programming language • for Android , JVM , Browser • Concise , Safe , Interoperable • work with Java echo system ( libraries, JRebel )

Slide 5

Slide 5 text

function

Slide 6

Slide 6 text

No content

Slide 7

Slide 7 text

First class citizen package boo.bar
 class A {
 fun foo(){
 }
 } 
 fun foo(){}

Slide 8

Slide 8 text

Function fun cal(x: Int = 1, y: Int = 2){ print("x+y=${x + y}”) // string template
 
 fun main(args: Array) {
 val a = A()
 cal(1) //default value
 cal(x = 3) 
 a.cal(x = 4, y = 5) // named param
 }
 


Slide 9

Slide 9 text

Function fun sum(x: Int, y: Int): Int {
 return x + y
 } fun sum(x: Int, y: Int): Int = x + y fun sum(x: Int, y: Int) = x + y

Slide 10

Slide 10 text

variable

Slide 11

Slide 11 text

No content

Slide 12

Slide 12 text

string template & conditional expressions

Slide 13

Slide 13 text

No content

Slide 14

Slide 14 text

Null safety var a: String = "abc"
 a = null //compilation error
 
 var b: String? = null // OK!
 b = bob?.department?.name // safe call using ?. val l = b!!.length() // YOYO (NPE-lovers)

Slide 15

Slide 15 text

Elvis operator val l: Int = if (b != null) b.length else -1
 
 val l = b?.length ?: -1

Slide 16

Slide 16 text

range

Slide 17

Slide 17 text

No content

Slide 18

Slide 18 text

When when (x) {
 0, 1 -> print("x == 0 or x == 1”) 2 -> print("x == 2") true -> print("true") is String -> x.startsWith("prefix") is File -> x.getFreeSpace() else -> { // Note the block
 print("x is funny")
 }
 }

Slide 19

Slide 19 text

Smart cast / Auto cast // Once type is checked, no need to cast again when (x) {
 is String -> x.length()
 is File -> x.getFreeSpace() else -> { // Note the block
 print("x is neither String nor File")
 } } // safe cast, x must be nullable val x: String? = y as? String

Slide 20

Slide 20 text

type safety recap - null safety

Slide 21

Slide 21 text

Equity val a: Int = 10000
 print(a == a) // Prints 'true'
 print(a === a) // Prints ‘true' 
 val boxedA: Int? = a
 val anotherBoxedA: Int? = a
 print(boxedA == anotherBoxedA) // 'true'
 print(boxedA === anotherBoxedA)// 'false'

Slide 22

Slide 22 text

Equity • Smaller types are NOT implicitly converted to bigger types val a: Int? = 1 // A boxed Int
 val b: Long? = a print(a == b) // Won’t compile

Slide 23

Slide 23 text

Exception • Exception is an expression val a: Int? = try { Int.parseInt("300") } catch (e: NumberFormatException) { null }
 • There’s no checked Exception [1] [2]

Slide 24

Slide 24 text

Class • Final by default. With Android in mind • Main constructor must be called • Parent’s constructor must be called class MyView : View {
 constructor(ctx: Context) : super(ctx) {
 }
 constructor(ctx: Context, attrs: AttributeSet) : super(ctx, attrs) {
 }
 }

Slide 25

Slide 25 text

data class

Slide 26

Slide 26 text

Data class // Declaration in Java public class Person(){ private String name; private int weight; // getter… setter… }


Slide 27

Slide 27 text

Data class // Declaration in Kotlin data class Person(val name: String,var weight: Int)
 val nevin = Person("Nevin",82)
 nevin.name = "Nevin Chen” // compile error 
 nevin.weight = 7 // ok

Slide 28

Slide 28 text

Data class val p2 = Person("Nevin", 82)
 val p3 = Person("Mark", 75)
 
 println("nevin == p2: ${nevin == p2}”) // true
 println("nevin == p3: ${nevin == p3}”) // false println(user.copy("Max", 0.33))

Slide 29

Slide 29 text

Lambda expression • function literal • Surrounded by curly braces, {} • parameters (if any) are declared before -> • The body goes after ->

Slide 30

Slide 30 text

Lambda val sum = { : Int, : Int -> } x y x + y

Slide 31

Slide 31 text

Lambda val sum : (Int,Int) -> Int = { , -> } x y x + y

Slide 32

Slide 32 text

Function expression // function expression val sum = fun(x: Int, y: Int): Int {
 return x + y
 } // anonymous function only val sum = fun(x: Int, y: Int): Int = x + y

Slide 33

Slide 33 text

Higher-order function // function that take functions as parameter, // or return a function fun calculate(x: Int, y: Int, formula: (Int, Int) -> Int) {
 println("the result is ${formula(x, y)}") } // usage
 fun main(args: Array) {
 calculate(1,5,sum)
 calculate(1,5, { x, y -> x + y }) calculate(1,5){ x, y -> x + y }
 calculate(1,5,fun(x: Int, y: Int): Int = x + y )
 }

Slide 34

Slide 34 text

Extension Function // Extension Function fun Int.sum(other: Int): Int = this + other
 // Extension Function Expressions
 val sum = fun Int.(other: Int): Int = this + other // usage 1.sum(2)

Slide 35

Slide 35 text

Sample // scope : within the same package fun Int.beforeKitkat(): Boolean{
 return this < Build.VERSION_CODES.KITKAT
 } if (Build.VERSION.SDK_INT.beforeKitkat()){
 // do something…
 }

Slide 36

Slide 36 text

Sample fun String.bd() = BigDecimal(this) fun main(args: Array) { //0.06
 println("0.05".bd().add("0.01".bd()) ) //0.060000000000000005
 println(0.05+0.01)
 }

Slide 37

Slide 37 text

Function Expression val validator: (String) -> Boolean = { it.length > 2 }
 
 
 fun EditText.validateWith(check: (String) -> Boolean){
 val content = this.text.toString()
 if (check(content)) {
 context.toast("Welcome $content!")
 } else {
 context.toast("Name not valid")
 }
 }


Slide 38

Slide 38 text

delegated property

Slide 39

Slide 39 text

No content

Slide 40

Slide 40 text

observable delegated property

Slide 41

Slide 41 text

No content

Slide 42

Slide 42 text

Anko • Why Anko ? (sample) • type safe builder for view • null-safe (findViewById(….) return null) • avoid XML parsing (save CPU and battery)

Slide 43

Slide 43 text

Anko val layout = LinearLayout(context)
 layout.orientation = LinearLayout.VERTICAL
 val name = EditText(act)
 val button = Button(act)
 button.text = "Say Hello"
 button.setOnClickListener {
 Toast.makeText(act, .....).show()
 } layout.addView(name) layout.addView(button)

Slide 44

Slide 44 text

Anko verticalLayout {
 val name = editText()
 button("Say Hello") {
 onClick { toast(“HI!,${name.text}!") }
 }
 }

Slide 45

Slide 45 text

Anko • Anko DSL preview plugin • Design Support Library compile ‘org.jetbrains.anko:anko-design:0.7.2’ • Work great if you create view programatically • Other good stuff

Slide 46

Slide 46 text

Anko longToast("Halo"))
 info(“info”) warn(“warn”) debug(“debug”) async {
 var result = readDataFromServer();
 uiThread {
 warn(result + "")
 halo.text = result
 }
 }

Slide 47

Slide 47 text

Android Extension // import import kotlinx.android.synthetic.layout.* // code
 txt.text= "WELCOME !!”// use widget id directly

Slide 48

Slide 48 text

Take Away • Less code , Less bug • Easy to read and code • Lambda • Extension function

Slide 49

Slide 49 text

How to….

Slide 50

Slide 50 text

calling Java from Kotlin

Slide 51

Slide 51 text

No content

Slide 52

Slide 52 text

calling Kotlin from Java

Slide 53

Slide 53 text

No content

Slide 54

Slide 54 text

Steps to convert • Start small (ex. convert POJO into data class) • When you got NPE , Cast Exception • Check all !!s , make them ? or non-null • Check the difference between Java and Kotlin

Slide 55

Slide 55 text

Static method • There’s no static in Kotlin. Use companion object // Declaration class SomeClass{
 companion object {
 fun method(){
 }
 }
 } // Usage SomeClass.Companion.method()

Slide 56

Slide 56 text

Mutable non-nullable lateinit var username: String


Slide 57

Slide 57 text

Immutable non-nullable val url: String by lazy { // compute the string
 if (isProduction){
 return@lazy "http://prod.url.com"
 }else{
 return@lazy "http://stg.url.com"
 }
 }

Slide 58

Slide 58 text

Other difference • Invariant array • No raw types • No private fields • Smaller type is not a subtype of bigger types • Calling Java code from Kotlin • Calling Kotlin from Java

Slide 59

Slide 59 text

Other tips • std-lib : let() , apply() , with() ,run(), use() • Not a completely new language, very handy • A great place to learn functional programming • Droidcon talks may not up-to-date. Some issues are fixed.

Slide 60

Slide 60 text

Other tips • How to return from lambda • Don’t use inheritance with data class • Pass in function instead of object • Almost everything in Kotlin is an expression ( can return value) • Just “convert Java code to Kotlin” and “Config Kotlin in Project”

Slide 61

Slide 61 text

Resources • Official materials , try.kotlinlang.org , and Slack(#android) • Koans web and github • Jake Wharton : Using Project Kotlin for Android and Advancing Development with the Kotlin • twitter #kotlin @cbeust @madisp [JRebel] • Links : antonio leva , Jcconf 2015

Slide 62

Slide 62 text

Testing

Slide 63

Slide 63 text

Testing • Sample Project( Android Testing) • Testing with Kotlin • Instrumentation Testing Robots

Slide 64

Slide 64 text

Usage • Swing: PokemonGoBot • Backend Fronten • Testing • Web , backend , and other list of Kotlin Projects • Hot on Github • Gradle (sample) (talk) (Groovy)

Slide 65

Slide 65 text

Thanks!