$30 off During Our Annual Pro Sale. View Details »

Kotlin Hands-on

Kotlin Hands-on

MorningTech on Kotlin

Laurent BARESSE

March 18, 2017
Tweet

More Decks by Laurent BARESSE

Other Decks in Technology

Transcript

  1. Develop a
    weather app
    with K

    View Slide

  2. Schedule
    9:00 - Introduction

    9:05 - Intro to Kotlin part 1

    9:25 - Project presentation & setup

    9:35 - Hands-on part 1 (55 minutes)

    10:30 - Coffee break

    10:45 - Intro to Kotlin part 2

    11:00 - Hands-on part 2 (55 minutes)

    11:55 - Final Part
    #androiddev #kotlin #morningtech @ekito

    View Slide

  3. Practical notes
    https://github.com/Ekito/2017-handson-kotlinAndroid
    Grab your stuff !
    #androiddev #kotlin #morningtech @ekito

    View Slide

  4. @Baresse
    Work @ ekito
    Developer & Geek
    Fullstack & Mobile
    Laurent BARESSE
    @arnogiu
    Work @ ekito
    Core & Gear Maker
    Mobile & Cloud
    Arnaud GIULIANI
    #androiddev #kotlin #morningtech @ekito

    View Slide

  5. https://www.ekito.fr/careers
    Join the team !
    #androiddev #kotlin #morningtech @ekito

    View Slide

  6. Intro to
    part 1
    #androiddev #kotlin #morningtech @ekito

    View Slide

  7. « production ready »
    15.02.2016
    #androiddev #kotlin #morningtech @ekito

    View Slide

  8. Kotlin 1.1.1 @ 15.03.2017
    #androiddev #kotlin #morningtech @ekito

    View Slide

  9. Yet another JVM
    Language ?
    #androiddev #kotlin #morningtech @ekito

    View Slide

  10. The new « Swift »
    for Android ?
    #androiddev #kotlin #morningtech @ekito

    View Slide

  11. #androiddev #kotlin #morningtech @ekito

    View Slide

  12. What’s
    Kotlin ?
    - Fully open source (built by Jetbrains)
    - Run on Java 6+
    - Static typing & type inference
    - Modern language features
    - 1st grade tooling
    #androiddev #kotlin #morningtech @ekito

    View Slide

  13. What’s inside
    Kotlin ?
    - String templates
    - Properties
    - Lambdas
    - Data class
    - Smart cast
    - Null safety
    - Lazy property
    - Default values for function
    parameters
    - Extension Functions
    - No more ;
    - Single-expression
    functions
    - When expression
    - let, apply, use, with
    - Collections
    - Android Extensions Plugin
    #androiddev #kotlin #morningtech @ekito

    View Slide

  14. Compare with
    Same conciseness and expressive code, but
    Kotlin static typing and null-safety make a big
    difference.
    "Some people say Kotlin has 80% the power of
    Scala, with 20% of the features" * 

    "Kotlin is a software engineering language in
    contrast to Scala which is a computing science
    language." *
    Swift and Kotlin are VERY similar. Swift is LLVM
    based and has C interop while Kotlin is JVM based
    and has Java interop.
    * Quotes from Kotlin: The Ying and Yang of Programming Languages
    #androiddev #kotlin #morningtech @ekito
    @
    sdeleuze

    View Slide

  15. is Kotlin Android friendly ?
    https://github.com/SidneyXu/AndroidDemoIn4Languages
    Method counts by Language
    #androiddev #kotlin #morningtech @ekito

    View Slide

  16. 16
    Let’s Go !
    #androiddev #kotlin #morningtech @ekito

    View Slide

  17. Typing & Inference
    val a: Int = 1

    val b = 1 // `Int` type is inferred
    var x = 5 // `Int` type is inferred

    x += 1
    Inferred values
    Mutable values
    val : constant value - IMMUTABLE
    var : variable value - MUTABLE
    USE VAL AS MUCH AS POSSIBLE !
    #androiddev #kotlin #morningtech @ekito

    View Slide

  18. Safety with Optionals
    var stringA: String = "foo"

    stringA = null //Compilation error - stringA is a String (non optional)


    var stringB: String? = "bar" // stringB is an Optional String

    stringB = null //ok
    Optional value
    #androiddev #kotlin #morningtech @ekito

    View Slide

  19. Late initialization, Lazy, Delegates …
    // set length default value manually

    val length = if (stringB != null) stringB.length else -1

    //or with the Elvis operator

    val length = stringB?.length ?: -1
    Default Value & Elvis Operator
    val length = stringB.length // Compilation error - stringB can be null !

    // use ? the safe call operator

    val length = stringB?.length //Value or null - length is type Int?
    val length = stringB!!.length // Value or explicit throw NPE - length is type Int
    Safe call with ?. or Explicit call with !!.
    #androiddev #kotlin #morningtech @ekito

    View Slide

  20. Example
    Working with optional values
    #androiddev #kotlin #morningtech @ekito

    View Slide

  21. Example
    #androiddev #kotlin #morningtech @ekito
    Null check safety & Smart cast
    Securing with default values

    View Slide

  22. Class
    class User (

    val userName: String,

    val firstName: String,

    val lastName: String,

    var location: Point? = null

    )
    POJO +
    - Getter
    - Setter
    - Constructors
    #androiddev #kotlin #morningtech @ekito
    public / closed by default

    View Slide

  23. Data Class
    data class User (

    val userName: String,

    val firstName: String,

    val lastName: String,

    var location: Point? = null

    )
    POJO +
    - Getter
    - Setter
    - Constructors
    - toString
    - hashcode
    - equals
    - copy
    #androiddev #kotlin #morningtech @ekito

    View Slide

  24. POJO ?
    Kotlin
    Java
    #androiddev #kotlin #morningtech @ekito

    View Slide

  25. Properties
    // readonly property

    val isEmpty: Boolean

    get() = this.size == 0
    Properties can be declared in constructor or in class
    You can also handle getter & setter
    // customer getter & setter

    var stringRepresentation: String
    set(value) {


    }
    class ApiKey(var weatherKey: String, var geocodeKey: String){

    var debug : Boolean = false

    }
    #androiddev #kotlin #morningtech @ekito

    View Slide

  26. Object Component
    // singleton

    object Resource {

    val name = "Name"

    }
    class StringCalculator{
    // class helper

    companion object{

    val operators = arrayOf("+","-","x","/")

    }

    }
    Singleton Class
    Companion Object
    #androiddev #kotlin #morningtech @ekito

    View Slide

  27. Example
    data class User(val name: String = "", val age: Int = 0)
    val jack = User(name = "Jack", age = 1) //no new keyword

    val anotherJack = jack.copy(age = 2)
    Data Class usage
    A simple GSon Class
    #androiddev #kotlin #morningtech @ekito

    View Slide

  28. When
    when (s) {

    1 -> print("x == 1")

    2 -> print("x == 2")

    else -> { // Note the block

    print("x is neither 1 nor 2")

    }

    }
    Flow Control (replace your old if blocks)
    in ->
    is ->
    expression ->
    when (x) {

    in 1..10 -> print("x is in the range")

    in validNumbers -> print("x is valid")

    !in 10..20 -> print("x is outside the range")

    else -> print("none of the above")

    }
    Pattern Matching
    #androiddev #kotlin #morningtech @ekito
    * can match with operators : in, as, is, range …

    View Slide

  29. Example
    #androiddev #kotlin #morningtech @ekito

    View Slide

  30. Collections
    // immutable map

    val map = mapOf("a" to 1, "b" to 2, "c" to 3)

    for ((k, v) in map) {

    println("$k -> $v")

    }

    map2["a"] = "my value" // direct map access with array style
    // range

    for (i in 1..100) { //... }
    #androiddev #kotlin #morningtech @ekito
    // immutable list

    val list = listOf("a", "b", "c","aa")

    list.filter { it.startsWith("a") }
    * collections operators : map, filter, take, flatMap, forEach, firstOrNull, last …

    View Slide

  31. Example
    Kotlin Collection
    Java 7 Collection
    #androiddev #kotlin #morningtech @ekito

    View Slide

  32. InterOp
    object UserSingleton{

    fun stringify(user : User) : String{

    val (name,age) = user

    return "[name=$name][age=$age]"

    }

    }


    fun WhatIsyourAge(user : User){

    println("Your age is ${user.age}")

    }


    data class User (val name: String, val age : Int){

    companion object{

    fun sayHello(user : User){

    println("Hello ${user.name}")

    }

    }

    }
    User u = new User("toto",42);

    User.Companion.sayHello(u);

    UserUtilsKt.WhatIsyourAge(u);

    System.out.println("stringify : "+UserSingleton.INSTANCE.stringify(u));
    Kotlin code
    Calling Kotlin from Java
    #androiddev #kotlin #morningtech @ekito

    View Slide

  33. Project presentation
    & setup
    #androiddev #kotlin #morningtech @ekito

    View Slide

  34. My Weather app
    #androiddev #kotlin #morningtech @ekito

    View Slide

  35. Get the project
    #androiddev #kotlin #morningtech @ekito
    https://github.com/Ekito/2017-handson-kotlinAndroid

    View Slide

  36. Create your branch
    #androiddev #kotlin #morningtech @ekito
    https://github.com/Ekito/2017-handson-kotlinAndroid/blob/master/README.pdf

    View Slide

  37. MainApplication MainActivity
    DailyForecastModel
    DialogHelper
    WeatherSDKUtil
    WeatherSDK
    #androiddev #kotlin #morningtech @ekito

    View Slide

  38. Hands-on
    part 1
    #androiddev #kotlin #morningtech @ekito

    View Slide

  39. 9:00 - Introduction

    9:05 - Intro to Kotlin part 1

    9:25 - Project presentation & setup

    9:35 - Hands-on part 1 (55 minutes)
    10:30 - Coffee break

    10:45 - Intro to Kotlin part 2

    11:00 - Hands-on part 2 (55 minutes)

    11:55 - Final Part
    #androiddev #kotlin #morningtech @ekito
    Hands-on !

    View Slide

  40. 9:00 - Introduction

    9:05 - Intro to Kotlin part 1

    9:25 - Project presentation & setup

    9:35 - Hands-on part 1 (55 minutes)

    10:30 - Coffee break
    10:45 - Intro to Kotlin part 2

    11:00 - Hands-on part 2 (55 minutes)

    11:55 - Final Part
    #androiddev #kotlin #morningtech @ekito
    Coffee Break !

    View Slide

  41. Intro to
    part 2
    #androiddev #kotlin #morningtech @ekito

    View Slide

  42. Sweet stuffs for
    #androiddev #kotlin #morningtech @ekito

    View Slide

  43. Kotlin’s Android
    Extensions
    apply plugin: 'com.android.application'
    apply plugin: ‘kotlin-android’
    apply plugin: ‘kotlin-android-extensions’ // if use extensions
    #androiddev #kotlin #morningtech @ekito

    View Slide

  44. Kotlin
    Java
    #androiddev #kotlin #morningtech @ekito
    * In Fragment : onViewCreated()

    View Slide

  45. Functions
    fun reformat(str: String,

    normalizeCase: Boolean = true,

    upperCaseFirstLetter: Boolean = true,

    wordSeparator: Char = ' '): String {


    }
    Named Parameters & default values
    reformat(str, true, true, '_') // old way to call

    reformat(str, wordSeparator = '_') // using default values & named params
    fun String.hello(): String = "Hello " + this
    val hi = "Arnaud !".hello()

    println("$hi") // Hello Arnaud !
    Extension
    #androiddev #kotlin #morningtech @ekito

    View Slide

  46. Lambdas
    val fab = findViewById(R.id.fab) as FloatingActionButton

    fab.setOnClickListener { view -> popLocationDialog(view) }
    A lambda expression or an anonymous function is a “function literal”, i.e. a function that is
    not declared, but passed immediately as an expression
    - A lambda expression is always surrounded by curly braces
    - Its parameters (if any) are declared before -> (parameter types may be omitted),
    - The body goes after -> (when present).
    myNumber.split("\n").flatMap { it.split(separator) }

    .map(Integer::parseInt)

    .map(::checkPositiveNumber)

    .filter { it <= 1000 }

    .sum()
    #androiddev #kotlin #morningtech @ekito
    * Method references are not surrounded by curly braces

    View Slide

  47. Reactive
    Programming
    #androiddev #kotlin #morningtech @ekito

    View Slide

  48. Lamba expressions
    Functional Programming
    Reactive Streams
    http://reactivex.io/documentation/operators.html
    http://www.reactive-streams.org/
    https://spring.io/blog/2016/06/07/notes-on-reactive-
    programming-part-i-the-reactive-landscape
    #androiddev #kotlin #morningtech @ekito

    View Slide

  49. Example - Rx/Retrofit
    Kotlin
    Java
    #androiddev #kotlin #morningtech @ekito

    View Slide

  50. Hands-on
    part 2
    #androiddev #kotlin #morningtech @ekito

    View Slide

  51. 9:00 - Introduction

    9:05 - Intro to Kotlin part 1

    9:25 - Project presentation & setup

    9:35 - Hands-on part 1 (55 minutes)

    10:30 - Coffee break

    10:45 - Intro to Kotlin part 2

    11:00 - Hands-on part 2 (55 minutes)
    11:55 - Final Part
    #androiddev #kotlin #morningtech @ekito
    Hands-on !

    View Slide

  52. Final Part
    #androiddev #kotlin #morningtech @ekito

    View Slide

  53. #androiddev #kotlin #morningtech @ekito
    Time is over !

    View Slide

  54. Smarter development for the JVM
    Kotlin
    #androiddev #kotlin #morningtech @ekito

    View Slide

  55. Thank you for
    coming
    #androiddev #kotlin #morningtech @ekito

    View Slide