Slide 1

Slide 1 text

Develop a reactive A app with K #DevFest Toulouse 2016

Slide 2

Slide 2 text

@arnogiu Work @ ekito App & Gear Maker Fullstack Mobile Dev Arnaud GIULIANI What’s ekito ?

Slide 3

Slide 3 text

3 « production ready » 15.02.2016

Slide 4

Slide 4 text

4 Yet another JVM Language ?

Slide 5

Slide 5 text

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

Slide 6

Slide 6 text

Limits of java - Verbose - Type inference - No properties / Lazy / Delegate - Checked exception - NullPointerException - Extensibility - End of lines with ; https://goo.gl/HIrmC9 @sdeleuze

Slide 7

Slide 7 text

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

Slide 8

Slide 8 text

What’s Kotlin ? - Built by Jetbrains & fully Open Source - Run on Java VM 6 & + - Static typing (type inference) - Modern language - Easy to Read & Learn - Concise & Fast to write - Fully interoperable with Java - 1st grade tooling

Slide 9

Slide 9 text

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

Slide 10

Slide 10 text

How K can help you ? - Reduce common errors & boiler code - Make safer API - Help keep focus on your business - Interoperable java alternative Can be used almost everywhere Java is used today !

Slide 11

Slide 11 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

Slide 12

Slide 12 text

Use Cases Source : poll on Kotlin Slack https://goo.gl/HIrmC9 @sdeleuze

Slide 13

Slide 13 text

13 Want some nougat ?

Slide 14

Slide 14 text

14 Slowing Deployment https://goo.gl/2sOGBd

Slide 15

Slide 15 text

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

Slide 16

Slide 16 text

16 Well … let’s get some Kotlin !

Slide 17

Slide 17 text

Develop & have fun with K * Being productive again !

Slide 18

Slide 18 text

18 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" } Actual Version : 1.0.4

Slide 19

Slide 19 text

19 IntelliJ - Plugin

Slide 20

Slide 20 text

20 IntelliJ - Menus

Slide 21

Slide 21 text

21 Typing & Inference val a: Int = 1
 val b = 1 // `Int` type is inferred
 val c: Int // Type required when no initializer is provided
 c = 1 // definite assignment var x = 5 // `Int` type is inferred
 x += 1 Infered values Mutable values val : constant value var : variable value

Slide 22

Slide 22 text

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 22 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 Safe call with ?. or Explicit call !!. Optional value

Slide 23

Slide 23 text

23 Safety again ! val name = "Arnaud"
 var s : String // Compilation error
 lateinit var s : String // late initialized variable // if s is not set throw an NPE
 fun testHello() {
 s = "Hello $name" //…
 } Lazy, Delegates … Late initialization // 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

Slide 24

Slide 24 text

24 Example - Activity

Slide 25

Slide 25 text

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

Slide 26

Slide 26 text

26 Data Class data class User (
 var userName: String,
 var firstName: String,
 var lastName: String,
 var location: Point? = null
 ) POJO + - Getter - Setter - Constructors - toString - hashcode - equals - copy

Slide 27

Slide 27 text

27 No Static, think Object // my resource singleton
 object Resource {
 val name = "Name"
 } println(" my resource is : ${Resource.name}") class StringCalculator{
 companion object{
 val operators = arrayOf("+","-","x","/")
 }
 } println(" my operators are : ${StringCalculator.operators}") Object (good old singleton ;-) ) Companion Object

Slide 28

Slide 28 text

28 Example data class User(val name: String = "", val age: Int = 0) val jack = User(name = "Jack", age = 1)
 val anotherJack = jack.copy(age = 2) json class data class handling

Slide 29

Slide 29 text

29 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) 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 in -> is -> expression -> when (s) {
 is String -> print("s is a string")
 else -> print("s is not a string")
 }

Slide 30

Slide 30 text

30 Example

Slide 31

Slide 31 text

31 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{
 return "Hello " + this
 } val hi = "Arnaud !".hello()
 println("$hi") // Hello Arnaud ! Extension

Slide 32

Slide 32 text

32 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). numberString.split("\n").flatMap { it.split(separator) }
 .map(Integer::parseInt)
 .map(::checkPositiveNumber)
 .filter { it <= 1000 }
 .sum()

Slide 33

Slide 33 text

33 Destructuring Data fun extractDelimiter(input: String): Pair {
 return … } val (separator, numberString) = extractDelimiter(input) data class User(var name : String,var age : Int) val toto = User("toto",42) // …
 val (name,age) = toto Returning two values with Pair Destructured values

Slide 34

Slide 34 text

34 Collections // immutable list
 val list = listOf("a", "b", "c","aa")
 list.filter { it.startsWith("a") } // immutable map
 val map = mapOf("a" to 1, "b" to 2, "c" to 3)
 for ((k, v) in map) {
 println("$k -> $v")
 } 
 // mutable map
 val map2 = HashMap() 
 // direct map access
 map2["a"] = "my value"
 println(map2["a"]) // range
 for (i in 1..100) { //... }

Slide 35

Slide 35 text

35 Java 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

Slide 36

Slide 36 text

Sweet stuffs for

Slide 37

Slide 37 text

Gradle tips for Kotlin # Gradle
 org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX: +HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
 org.gradle.parallel=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 38

Slide 38 text

38 Kotlin’s Android Extensions android { ... sourceSets { main.java.srcDirs += 'src/main/kotlin' } } apply plugin: 'com.android.application' apply plugin: ‘kotlin-android’ apply plugin: ‘kotlin-android-extensions’ // if use extensions In your build.gradle

Slide 39

Slide 39 text

Android Extensions No more findViewById !!! Kotlin Java

Slide 40

Slide 40 text

Anko - Android Dev on steroïds Async task in few lines doAsync { // Long background task uiThread { result.text = "Done" } } Layout DSL verticalLayout { val name = editText() button("Say Hello") { onClick { toast("Hello, ${name.text}!") } } } https://github.com/Kotlin/anko

Slide 41

Slide 41 text

No content

Slide 42

Slide 42 text

Reactive Programming

Slide 43

Slide 43 text

Reactive Programming 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 44

Slide 44 text

44 Example - Rx/Retrofit Kotlin Java

Slide 45

Slide 45 text

45 Example - Rx/Realm

Slide 46

Slide 46 text

46 Learning Kotlin

Slide 47

Slide 47 text

47 Try Kotlin online http://try.kotlinlang.org/#/Examples/ Kotlin Reference https://kotlinlang.org/docs/reference/ Kotlin Cheat Sheet (by ekito) http://www.slideshare.net/arnaudgiuliani/kotlin- cheat-sheet-by-ekito Kotlin Community https://kotlinlang.org/community.html

Slide 48

Slide 48 text

48 Kotlin 1.1

Slide 49

Slide 49 text

49 Demo ! https://github.com/Ekito/reactiveweather-android

Slide 50

Slide 50 text

50 The Reactive Weather App Demo My Weather App Google Geocode WS Wunderground WS Weather SDK Last Weather

Slide 51

Slide 51 text

Thank you :)