Slide 1

Slide 1 text

Develop your next app with Kotlin

Slide 2

Slide 2 text

@arnogiu Work @ ekito Core & Gear Maker Mobile & Cloud Arnaud GIULIANI

Slide 3

Slide 3 text

« production ready » 15.02.2016

Slide 4

Slide 4 text

1.1.1 @ 15.03.2017

Slide 5

Slide 5 text

Yet another JVM Language ?

Slide 6

Slide 6 text

The new « Swift » for Android ? https://goo.gl/W5g6Do - mid 2014

Slide 7

Slide 7 text

Limits of java - Verbose - Type inference - No properties / Lazy / Delegate - Checked exception - NullPointerException - Extensibility - End of lines with ; @ sdeleuze

Slide 8

Slide 8 text

But Java is great … - Fast - Optimized bytecode - Static typing - Simple to learn - Amazing ecosystem

Slide 9

Slide 9 text

No content

Slide 10

Slide 10 text

- Conciseness & Smarter API - Null Safety & Immutability protection - Type Inference, Static Typing & Smart Casts - Open programming styles - Java Interop Why Kotlin ?

Slide 11

Slide 11 text

What’s Kotlin ? - Fully open source (built by Jetbrains) - Based on Java & run on Java 6+ - Modern language features - 1st grade tooling

Slide 12

Slide 12 text

More About 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

Slide 13

Slide 13 text

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 @ sdeleuze

Slide 14

Slide 14 text

is Kotlin Android friendly ? https://github.com/SidneyXu/AndroidDemoIn4Languages Method counts by Language

Slide 15

Slide 15 text

Java 8 on Android ? https://android-developers.googleblog.com/2017/03/future-of-java-8-language-feature.html

Slide 16

Slide 16 text

KOTLIN is not just about writing your app with lesser lines. It’s all about writing SAFER & BETTER APPS !

Slide 17

Slide 17 text

Kotlin clearly considered by the Java community ! https://spring.io/blog/2017/01/04/introducing-kotlin-support-in- spring-framework-5-0 http://www.javamagazine.mozaicreader.com/ #&pageSet=5&page=0&contentItem=0 (March/April 2017) https://www.thoughtworks.com/radar/languages-and-frameworks/kotlin

Slide 18

Slide 18 text

Ready to use Easy to run

Slide 19

Slide 19 text

19 IntelliJ

Slide 20

Slide 20 text

20

Slide 21

Slide 21 text

Getting started with gradle buildscript { ext.kotlin_version = '' dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } apply plugin: "kotlin" dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" }

Slide 22

Slide 22 text

Gradle tips for Kotlin # Gradle
 org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX: +HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
 org.gradle.parallel=true org.gradle.deamon=true
 
 # Kotlin
 kotlin.incremental=true
 
 # Android Studio 2.2+
 android.enableBuildCache=true In your gradle.properties https://medium.com/keepsafe-engineering/kotlin-vs-java-compilation-speed-e6c174b39b5d#.k44v7axsk

Slide 23

Slide 23 text

Let’s go !

Slide 24

Slide 24 text

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 !

Slide 25

Slide 25 text

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 with ?

Slide 26

Slide 26 text

// 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 !!.

Slide 27

Slide 27 text

Example Working with optional values

Slide 28

Slide 28 text

Example Null check safety & Smart cast Securing with default values

Slide 29

Slide 29 text

Class class User (
 val userName: String,
 val firstName: String,
 val lastName: String,
 var location: Point? = null
 ) POJO + - Getter - Setter - Constructors

Slide 30

Slide 30 text

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

Slide 31

Slide 31 text

POJO ? Kotlin Java

Slide 32

Slide 32 text

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 lateinit var weatherWS : WeatherWS
 
 @Test
 fun testMyWeatherWS() {
 weatherWS = Inject.get()
 // ... 
 } class ApiKey(var weatherKey: String, var geocodeKey: String){
 var debug : Boolean = false
 } Late & Lazy initialization

Slide 33

Slide 33 text

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

Slide 34

Slide 34 text

Object Class // singleton
 object Resource {
 val name = "Name"
 } class StringCalculator{ // class helper
 companion object{
 val operators = arrayOf("+","-","x","/")
 }
 } Singleton Class Companion Object

Slide 35

Slide 35 text

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 switch and if-blocks) 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

Slide 36

Slide 36 text

Example Page Adapter Menu Select

Slide 37

Slide 37 text

Collections // immutable map
 val map = mapOf("a" to 1, "b" to 2, "c" to 3)
 for ((k, v) in map) {
 println("$k -> $v")
 } 
 map["a"] = "my value" // direct map access with array style // range
 for (i in 1..100) { //... } // immutable list
 val list = listOf("a", "b", "c","aa")
 list.filter { it.startsWith("a") } * collections operators : map, filter, take, flatMap, forEach, firstOrNull, last …

Slide 38

Slide 38 text

Example Kotlin Collection Java 7 Collection

Slide 39

Slide 39 text

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() * Method references are not surrounded by curly braces !

Slide 40

Slide 40 text

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

Slide 41

Slide 41 text

Extensions Functions Extension declaration Usage

Slide 42

Slide 42 text

Destructuring Declarations In lambdas, Since Kotlin 1.1 map.mapValues { (key, value) -> "$value!" } Destructured variables declaration val person = Person("john",31) //data class Person(val name:String, val age : Int)
 val (name,age) = person
 println("I'm $name, my age is $age") * Works with Map, Data Class, Pair, Triple … => you can return 2 values in function !

Slide 43

Slide 43 text

InterOp Kotlin/Java Java Kotlin

Slide 44

Slide 44 text

InterOp Java/Kotlin object UserSingleton{
 fun stringify(user : User) : String{
 // …
 }
 } 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){ //…
 }
 }
 } User u = new User("toto",42);
 User.Companion.sayHello(u); UserUtilsKt.WhatIsyourAge(u); UserSingleton.INSTANCE.stringify(u)

Slide 45

Slide 45 text

Sweet stuffs for

Slide 46

Slide 46 text

Kotlin’s Android Extensions apply plugin: 'com.android.application' apply plugin: ‘kotlin-android’ apply plugin: ‘kotlin-android-extensions’ // the kotlin-android extension ! In your build.gradle

Slide 47

Slide 47 text

Kotlin Java

Slide 48

Slide 48 text

Reactive Programming

Slide 49

Slide 49 text

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

Slide 50

Slide 50 text

Example - Rx/Retrofit Kotlin Java 7

Slide 51

Slide 51 text

Example - Rx/Realm Load first element & update UI

Slide 52

Slide 52 text

52 Ready to Go ?

Slide 53

Slide 53 text

53 Just another hype JVM stuff ?

Slide 54

Slide 54 text

54 Production ready ?

Slide 55

Slide 55 text

It’s always hard to start !

Slide 56

Slide 56 text

Our feedback - Easy to start on existing project - Great learning curve - Good doc & tools support - Don’t use anymore Butterknife, Dagger … - T_T hard to come back to Java https://www.ekito.fr/people/kotlin-in-production-one-year-later/

Slide 57

Slide 57 text

IF YOU DON'T LOOK AT JAVA AND THINK, "THIS COULD BE BETTER", DON'T SWITCH. @RunChristinaRun (Pinterest)

Slide 58

Slide 58 text

No content

Slide 59

Slide 59 text

Try Kotlin online http://try.kotlinlang.org/#/Examples/ Kotlin Reference https://kotlinlang.org/docs/reference/ Kotlin Cheat Sheet (by ekito) https://speakerdeck.com/agiuliani/kotlin-cheat- sheet

Slide 60

Slide 60 text

70% Less ! Develop a weather app with K https://github.com/Ekito/2017-handson-kotlinAndroid

Slide 61

Slide 61 text

Thank you :)