Slide 1

Slide 1 text

Beyond Kotlin Advanced features for API makers

Slide 2

Slide 2 text

Work @ ekito Mobile & Cloud Kotlin Lover @arnogiu Arnaud GIULIANI medium.com/@giuliani.arnaud/ ekito.fr/people #DevFestToulouse

Slide 3

Slide 3 text

No content

Slide 4

Slide 4 text

No content

Slide 5

Slide 5 text

Statically typed programming language for modern multiplatform applications

Slide 6

Slide 6 text

No content

Slide 7

Slide 7 text

Kotlin on Android, now official

Slide 8

Slide 8 text

h5ps:/ /spring.io/blog/2017/01/04/introducing-kotlin-support-in-spring- framework-5-0 h5p:/ /www.javamagazine.mozaicreader.com/ #&pageSet=5&page=0&contentItem=0 (March/ April 2017) h5ps:/ /www.thoughtworks.com/radar/languages-and-frameworks/kotlin

Slide 9

Slide 9 text

h5ps:/ /zeroturnaround.com/rebellabs/developer-producNvity-report-2017-why-do-you-use-java-tools-you-use/

Slide 10

Slide 10 text

No content

Slide 11

Slide 11 text

Many well-known companies are using Kotlin: Pinterest, Coursera, NeUlix, Uber, Square, Trello, Basecamp, amongst others well-known banks (such as Goldman Sachs, Wells Fargo, J.P. Morgan, Deutsche Bank, UBS, HSBC, BNP Paribas, Société Générale)

Slide 12

Slide 12 text

No content

Slide 13

Slide 13 text

KOTLIN is not just a syntactic sugar It’s all about writing SAFER & BETTER APPS !

Slide 14

Slide 14 text

val / var Null safety Class / Object Lambda Functions Data Class Properties & delegates Default Values Named Parameters Extension Functions InterOp Not today!

Slide 15

Slide 15 text

No content

Slide 16

Slide 16 text

Let’s take a concrete context

Slide 17

Slide 17 text

// A Bean Definition data class BeanDefinition(val name: String, val clazz: KClass<*>) like dependency injection An advanced API development use case Let’s take

Slide 18

Slide 18 text

Before, we need some APIs ⚒

Slide 19

Slide 19 text

Writing Lambda APIs

Slide 20

Slide 20 text

// A Bean definition val beanDef: BeanDefinition? // let beanDef?.let { println("bean name is '${it.name}'") } // let & assign value val complexName: String? = beanDef?.let { "name : ${it.name} & class ${it.clazz}" } Safely executing with let // A Bean definition val beanDef: BeanDefinition? // let beanDef?.let { println("bean name is '${it.name}'") }

Slide 21

Slide 21 text

// takeIf (validate predicate) val bean = beanDef?.takeIf { it.name.isNotEmpty() } val bean = beanDef?.takeUnless { it.name.isNullOrEmpty() } // A Bean definition val beanDef: BeanDefinition? = ... // Guard like expression val bean: BeanDefinition = beanDef?.takeIf { it.name.isNotEmpty() } ?: error("bean name is empty") // Guard like expression val bean: BeanDefinition = beanDef?.takeIf { it.name.isNotEmpty() } ?: error("bean name is empty") val bean: BeanDefinition = beanDef?.takeIf { it.name.isNotEmpty() } ?: return // takeIf (validate predicate) val bean = beanDef?.takeIf { it.name.isNotEmpty() } val bean = beanDef?.takeUnless { it.name.isNullOrEmpty() } takeIf & takeUnless // A Bean definition val beanDef: BeanDefinition? = ...

Slide 22

Slide 22 text

let ~ run -> return last value also ~ apply -> return itself with() -> function & return last value it let ~ run -> return last value also ~ apply -> return itself with() -> function & return last value this

Slide 23

Slide 23 text

Encapsulate behavior for a target object

Slide 24

Slide 24 text

Lambda function Receiver Type fun T.function( (T) -> R) fun T.function( T.() -> R) Writing encapsulation public inline fun T.apply(block: T.() -> Unit): T { block(); return this } public inline fun T.also(block: (T) -> Unit): T { block(this); return this } public inline fun T.apply(block: T.() -> Unit): T { block(); return this } public inline fun T.also(block: (T) -> Unit): T { block(this); return this } public inline fun T.apply(block: T.() -> Unit): T { block(); return this } public inline fun T.also(block: (T) -> Unit): T { block(this); return this } public inline fun T.apply(block: T.() -> Unit): T { block(); return this } public inline fun T.also(block: (T) -> Unit): T { block(this); return this }

Slide 25

Slide 25 text

SAM Conversion public class JavaBeanDefinition { String name; Class clazz; public JavaBeanDefinition(String name, Class clazz) {...} public void postInit(JavaInitializingBean initBean){ // Register post init } } public interface JavaInitializingBean { void onInitDone(); } val clazz = MyService::class.java val javaBean = JavaBeanDefinition(clazz.simpleName,clazz) public class JavaBeanDefinition { String name; Class clazz; public JavaBeanDefinition(String name, Class clazz) {...} public void postInit(JavaInitializingBean initBean){ // Register post init } } public interface JavaInitializingBean { void onInitDone(); } val clazz = MyService::class.java val javaBean = JavaBeanDefinition(clazz.simpleName,clazz) javaBean.postInit { println("bean has been defined ! ") } JAVA JAVA

Slide 26

Slide 26 text

The functional way // A Bean definition with post init data class BeanDefinition(val name: String, val clazz: KClass<*>) { fun postInit(initializingBean: InitializingBean) { // register post init ... } } // A Bean definition with post init data class BeanDefinition(val name: String, val clazz: KClass<*>) { fun postInit(initializingBean: () -> Unit) { // register post init ... } } val clazz = MyService::class val bean = BeanDefinition(clazz.java.simpleName, clazz) val clazz = MyService::class val bean = BeanDefinition(clazz.java.simpleName, clazz) bean.postInit { println("bean has been defined ! ") }

Slide 27

Slide 27 text

Types

Slide 28

Slide 28 text

Types Hierarchy

Slide 29

Slide 29 text

Types Hierarchy (again) ? ?

Slide 30

Slide 30 text

Dealing with generics sealed class BeanDefinition(val name : String, val clazz : KClass<*>) class Singleton(n : String, c : KClass<*>) : BeanDefinition(n,c) class Factory(n : String, c : KClass<*>) : BeanDefinition(n,c) fun registerBean(def: T) { //... } // Limit with Bounds fun registerBean(def: T) { //... }

Slide 31

Slide 31 text

Dealing with generics sealed class BeanDefinition(val name : String, val clazz : KClass<*>) class Singleton(n : String, c : KClass<*>) : BeanDefinition(n,c) class Factory(n : String, c : KClass<*>) : BeanDefinition(n,c) fun registerBean(def: T) { //... } class BeanProvider { } // Limit with Bounds fun registerBean(def: T) { //... } // Limit with Bounds fun registerBean(def: T) { //... } sealed class BeanDefinition(val name : String, val clazz : KClass<*>) class Singleton(n : String, c : KClass<*>) : BeanDefinition(n,c) class Factory(n : String, c : KClass<*>) : BeanDefinition(n,c)

Slide 32

Slide 32 text

Reified Types fun declareBean(name :String, clazz : KClass<*>){ val bean = BeanDefinition(name,clazz) }

Slide 33

Slide 33 text

Reified Types fun declareBean(name :String, clazz : KClass<*>){ val bean = BeanDefinition(name,clazz) } fun declareBean(name :String, clazz : T){ val bean = BeanDefinition(name,???) } fun declareBean(name :String, clazz : T){ // Capture Type parameter class val clazz = T::class val bean = BeanDefinition(name,clazz) }

Slide 34

Slide 34 text

Reified Types fun declareBean(name :String, clazz : KClass<*>){ val bean = BeanDefinition(name,clazz) } fun declareBean(name :String, clazz : T){ val bean = BeanDefinition(name,???) } fun declareBean(name :String, clazz : T){ // Capture Type parameter class val clazz = T::class val bean = BeanDefinition(name,clazz) } inline fun declareBean(name :String, clazz : T){ // Capture Type parameter class val clazz = T::class val bean = BeanDefinition(name,clazz) }

Slide 35

Slide 35 text

Reified Types fun declareBean(name :String, clazz : KClass<*>){ val bean = BeanDefinition(name,clazz) } fun declareBean(name :String, clazz : T){ val bean = BeanDefinition(name,???) } fun declareBean(name :String, clazz : T){ // Capture Type parameter class val clazz = T::class val bean = BeanDefinition(name,clazz) } inline fun declareBean(name :String, clazz : T){ // Capture Type parameter class val clazz = T::class val bean = BeanDefinition(name,clazz) } inline fun declareBean(){ // Capture Type parameter class val clazz = T::class val name = clazz.simpleName ?: "" val bean = BeanDefinition(name,clazz) }

Slide 36

Slide 36 text

Reified Types fun declareBean(name :String, clazz : KClass<*>){ val bean = BeanDefinition(name,clazz) } fun declareBean(name :String, clazz : T){ val bean = BeanDefinition(name,???) } fun declareBean(name :String, clazz : T){ // Capture Type parameter class val clazz = T::class val bean = BeanDefinition(name,clazz) } inline fun declareBean(name :String, clazz : T){ // Capture Type parameter class val clazz = T::class val bean = BeanDefinition(name,clazz) } inline fun declareBean(){ // Capture Type parameter class val clazz = T::class val name = clazz.simpleName ?: "" val bean = BeanDefinition(name,clazz) } inline fun declareBean(){ // Capture Type parameter class val clazz = T::class val name = clazz.simpleName ?: "" val bean = BeanDefinition(name,clazz) } declareBean()

Slide 37

Slide 37 text

Type Aliases typealias BeanList = List typealias BeanList = List val list : BeanList = listOf()

Slide 38

Slide 38 text

Type Aliases typealias BeanList = List typealias BeanList = List val list : BeanList = listOf() typealias BeanValidator = (BeanDefinition) -> Boolean typealias BeanList = List val list : BeanList = listOf() typealias BeanValidator = (BeanDefinition) -> Boolean val bv : BeanValidator = { def -> def.name.isNotEmpty()}

Slide 39

Slide 39 text

Type Aliases typealias BeanList = List typealias BeanList = List val list : BeanList = listOf() typealias BeanValidator = (BeanDefinition) -> Boolean typealias BeanList = List val list : BeanList = listOf() typealias BeanValidator = (BeanDefinition) -> Boolean val bv : BeanValidator = { def -> def.name.isNotEmpty()} typealias BeanValidator = (BeanDefinition) -> Boolean val bv : BeanValidator = { def -> def.name.isNotEmpty()} // A Bean definition with post init data class BeanDefinition(val name: String, val clazz: KClass<*>) { fun validate(validator: BeanValidator) : Boolean = validator(this) } // A Bean definition with post init data class BeanDefinition(val name: String, val clazz: KClass<*>) { fun validate(validator: BeanValidator) : Boolean = validator(this) }

Slide 40

Slide 40 text

Type Aliases typealias BeanList = List typealias BeanList = List val list : BeanList = listOf() typealias BeanValidator = (BeanDefinition) -> Boolean typealias BeanList = List val list : BeanList = listOf() typealias BeanValidator = (BeanDefinition) -> Boolean val bv : BeanValidator = { def -> def.name.isNotEmpty()} typealias BeanValidator = (BeanDefinition) -> Boolean val bv : BeanValidator = { def -> def.name.isNotEmpty()} // A Bean definition with post init data class BeanDefinition(val name: String, val clazz: KClass<*>) { fun validate(validator: BeanValidator) : Boolean = validator(this) } // A Bean definition with post init data class BeanDefinition(val name: String, val clazz: KClass<*>) { fun validate(validator: BeanValidator) : Boolean = validator(this) } // A Bean definition with post init data class BeanDefinition(val name: String, val clazz: KClass<*>) { fun validate(validator: BeanValidator) : Boolean = validator(this) }

Slide 41

Slide 41 text

No content

Slide 42

Slide 42 text

Ready to write our API

Slide 43

Slide 43 text

Making clean syntax StringUtil.capitalize(s) s.capitalize() Extension FuncNon 1.to("one") 1 to "one" Infix call set.add(2) set += 2 Operator overloading map.get("key") map["key"] Get method convenNon StringUtil.capitalize(s) 1.to("one") set.add(2) map.get("key")

Slide 44

Slide 44 text

file.use({f -> f.read()}) file.use {f -> f.read()} Lambda outside parenthesis sb.append("yes") sb.append("no") with (sb){ append("yes") append("no") } Lambda with receiver file.use({f -> f.read()}) sb.append("yes") sb.append("no") Making clean syntax

Slide 45

Slide 45 text

API or DSL?

Slide 46

Slide 46 text

DSL - a small set of features - focus on a particular task declarative API - a set of functions and procedures - for creation of applications imperative => internal DSL

Slide 47

Slide 47 text

Dependency injection DSL

Slide 48

Slide 48 text

provide { MyService() } Builder function Type reference () -> MyService MyService::class fun provide( definition : () -> T )

Slide 49

Slide 49 text

provide { MyServiceA() } declareContext { } provide { MyServiceB( ? ) } provide { MyServiceC( ? , ?) } data class MyServiceA() data class MyServiceB(val a : MyServiceA) data class MyServiceC(val a : MyServiceA, val b : MyServiceB) provide { MyServiceC(get(),get()) } provide { MyServiceB(get()) }

Slide 50

Slide 50 text

fun provide(definition: () -> T) { } data class BeanDefinition(val name: String, val clazz: KClass<*>)

Slide 51

Slide 51 text

fun provide(definition: () -> T) { val clazz = T::class val name = clazz.java.simpleName val bean = BeanDefinition(name,clazz) } data class BeanDefinition(val name: String, val clazz: KClass<*>)

Slide 52

Slide 52 text

inline fun provide(definition: () -> T) { val clazz = T::class val name = clazz.java.simpleName val bean = BeanDefinition(definition, name, clazz) } data class BeanDefinition(val name: String, val clazz: KClass<*>)

Slide 53

Slide 53 text

inline fun provide(definition: () -> T) { val clazz = T::class val name = clazz.java.simpleName val bean = BeanDefinition(definition, name, clazz) } data class BeanDefinition(val definition: () -> T, val name : String, val clazz : KClass<*>)

Slide 54

Slide 54 text

inline fun provide(noinline definition: () -> T) { val clazz = T::class val name = clazz.java.simpleName val bean = BeanDefinition(definition, name, clazz) } data class BeanDefinition(val definition: () -> T, val name : String, val clazz : KClass<*>)

Slide 55

Slide 55 text

class Context { inline fun provide(noinline definition: () -> T) { val clazz = T::class val name = clazz.java.simpleName val bean = BeanDefinition(definition, name, clazz) } } data class BeanDefinition(val definition: () -> T, val name : String, val clazz : KClass<*>)

Slide 56

Slide 56 text

class Context { var definitions = listOf>() inline fun provide(noinline definition: () -> T) { val clazz = T::class val name = clazz.java.simpleName definitions += BeanDefinition(definition, name, clazz) } } data class BeanDefinition(val definition: () -> T, val name : String, val clazz : KClass<*>)

Slide 57

Slide 57 text

class Context { var definitions = listOf>() inline fun provide(noinline definition: () -> T) { val clazz = T::class val name = clazz.java.simpleName definitions += BeanDefinition(definition, name, clazz) } } data class BeanDefinition(val definition: () -> T, val name : String, val clazz : KClass<*>) fun declareContext(init: Context.() -> Unit) = Context().apply(init)

Slide 58

Slide 58 text

class Context { var definitions = listOf>() inline fun provide(noinline definition: () -> T) { val clazz = T::class val name = clazz.java.simpleName definitions += BeanDefinition(definition, name, clazz) } } data class BeanDefinition(val definition: () -> T, val name : String, val clazz : KClass<*>) fun declareContext(init: Context.() -> Unit) = Context().apply(init)

Slide 59

Slide 59 text

class Context { var definitions = listOf>() inline fun provide(noinline definition: () -> T) { val clazz = T::class val name = clazz.java.simpleName definitions += BeanDefinition(definition, name, clazz) } } data class BeanDefinition(val definition: () -> T, val name : String, val clazz : KClass<*>) fun declareContext(init: Context.() -> Unit) = Context().apply(init)

Slide 60

Slide 60 text

declareContext { } provide { MyServiceB( ? ) } provide { MyServiceC( ? , ?) } data class MyServiceA() data class MyServiceB(val a : MyServiceA) data class MyServiceC(val a : MyServiceA, val b : MyServiceB) provide { MyServiceA() } provide { MyServiceC(get(),get()) } provide { MyServiceB(get()) }

Slide 61

Slide 61 text

class Context { var definitions = listOf>() inline fun provide(noinline definition: () -> T) { val clazz = T::class val name = clazz.java.simpleName definitions += BeanDefinition(definition, name, clazz) } } data class BeanDefinition(val definition: () -> T, val name: String, val clazz: KClass<*>) fun declareContext(init: Context.() -> Unit) = Context().apply(init)

Slide 62

Slide 62 text

data class BeanDefinition(val definition: () -> T, val name: String, val clazz: KClass<*>) fun declareContext(init: Context.() -> Unit) = Context().apply(init) class Context { var definitions = listOf>() inline fun provide(noinline definition: () -> T) { val clazz = T::class val name = clazz.java.simpleName definitions += BeanDefinition(definition, name, clazz) } } var instances = HashMap,Any>()

Slide 63

Slide 63 text

data class BeanDefinition(val definition: () -> T, val name: String, val clazz: KClass<*>) fun declareContext(init: Context.() -> Unit) = Context().apply(init) class Context { var definitions = listOf>() inline fun provide(noinline definition: () -> T) { val clazz = T::class val name = clazz.java.simpleName definitions += BeanDefinition(definition, name, clazz) } fun get() : T{} } var instances = HashMap,Any>()

Slide 64

Slide 64 text

data class BeanDefinition(val definition: () -> T, val name: String, val clazz: KClass<*>) fun declareContext(init: Context.() -> Unit) = Context().apply(init) class Context { var definitions = listOf>() inline fun provide(noinline definition: () -> T) { val clazz = T::class val name = clazz.java.simpleName definitions += BeanDefinition(definition, name, clazz) } fun get() : T = instances[T::class] } var instances = HashMap,Any>()

Slide 65

Slide 65 text

data class BeanDefinition(val definition: () -> T, val name: String, val clazz: KClass<*>) fun declareContext(init: Context.() -> Unit) = Context().apply(init) class Context { var definitions = listOf>() inline fun provide(noinline definition: () -> T) { val clazz = T::class val name = clazz.java.simpleName definitions += BeanDefinition(definition, name, clazz) } inline fun get() : T = instances[T::class] } var instances = HashMap,Any>()

Slide 66

Slide 66 text

data class BeanDefinition(val definition: () -> T, val name: String, val clazz: KClass<*>) fun declareContext(init: Context.() -> Unit) = Context().apply(init) class Context { var definitions = listOf>() inline fun provide(noinline definition: () -> T) { val clazz = T::class val name = clazz.java.simpleName definitions += BeanDefinition(definition, name, clazz) } inline fun get() : T = instances[T::class] as T } var instances = HashMap,Any>()

Slide 67

Slide 67 text

provide { MyServiceA() } declareContext { } provide { MyServiceB( ? ) } provide { MyServiceC( ? , ?) } data class MyServiceA() : MyServiceA data class MyServiceB(val a : MyServiceA) data class MyServiceC(val a : MyServiceA, val b : MyServiceB) provide { MyServiceC(get(),get()) } provide { MyServiceB(get()) }

Slide 68

Slide 68 text

provide { MyServiceA() } declareContext { } provide { MyServiceB( ? ) } provide { MyServiceC( ? , ?) } data class MyServiceA() : MyServiceA data class MyServiceB(val a : MyServiceA) data class MyServiceC(val a : MyServiceA, val b : MyServiceB) provide { MyServiceC(get(),get()) } provide { MyServiceB(get()) } Lazy evaluated by nature!

Slide 69

Slide 69 text

provide { MyServiceA() } declareContext { } data class MyServiceA() : MyServiceA data class MyServiceB(val a : MyServiceA) data class MyServiceC(val a : MyServiceA, val b : MyServiceB) provide { MyServiceC(get(),get()) } provide { MyServiceB(get()) }

Slide 70

Slide 70 text

data class BeanDefinition(val definition: () -> T, val name: String, val clazz: KClass<*>) fun declareContext(init: Context.() -> Unit) = Context().apply(init) class Context { var definitions = listOf>() inline fun provide(noinline definition: () -> T) { val clazz = T::class val name = clazz.java.simpleName definitions += BeanDefinition(definition, name, clazz) } inline fun get() : T = instances[T::class] as T } var instances = HashMap,Any>()

Slide 71

Slide 71 text

data class BeanDefinition(val definition: () -> T, val name: String, val clazz: KClass<*>) fun declareContext(init: Context.() -> Unit) = Context().apply(init) class Context {...} var instances = HashMap,Any>()

Slide 72

Slide 72 text

data class BeanDefinition(val definition: () -> T, val name: String, val clazz: KClass<*>) abstract class Module { abstract fun context() : Context } class Context {...} var instances = HashMap,Any>()

Slide 73

Slide 73 text

data class BeanDefinition(val definition: () -> T, val name: String, val clazz: KClass<*>) abstract class Module { abstract fun context() : Context fun declareContext(init: Context.() -> Unit) = Context().apply(init) } class Context {...} var instances = HashMap,Any>()

Slide 74

Slide 74 text

class SimpleModule : Module() { override fun context() = declareContext { provide { ServiceA() } provide { ServiceB(get()) } provide { ServiceC(get(), get()) } } } data class MyServiceA() data class MyServiceB(val a : MyServiceA) data class MyServiceC(val a : MyServiceA, val b : MyServiceB) Entirely declarative

Slide 75

Slide 75 text

Dependency resolution API

Slide 76

Slide 76 text

data class BeanDefinition(val definition: () -> T, val name: String, val clazz: KClass<*>) abstract class Module { abstract fun context() : Context fun declareContext(init: Context.() -> Unit) = Context().apply(init) } class Context {...} var instances = HashMap,Any>()

Slide 77

Slide 77 text

data class BeanDefinition(val definition: () -> T, val name: String, val clazz: KClass<*>) class Context {...} abstract class Module { abstract fun context() : Context fun declareContext(init: Context.() -> Unit) = Context().apply(init) } class CoreContext{ var instances = HashMap,Any>() var definitions = listOf>() }

Slide 78

Slide 78 text

data class BeanDefinition(val definition: () -> T, val name: String, val clazz: KClass<*>) class Context {...} abstract class Module(){ lateinit var coreContext: CoreContext abstract fun context() : Context fun declareContext(init: Context.() -> Unit) = Context(coreContext).apply(init) } class CoreContext{ var instances = HashMap,Any>() var definitions = listOf>() }

Slide 79

Slide 79 text

data class BeanDefinition(val definition: () -> T, val name: String, val clazz: KClass<*>) class Context {...} abstract class Module(){ lateinit var coreContext: CoreContext abstract fun context() : Context fun declareContext(init: Context.() -> Unit) = Context(coreContext).apply(init) } class CoreContext{ var instances = HashMap,Any>() var definitions = listOf>() }

Slide 80

Slide 80 text

data class BeanDefinition(val definition: () -> T, val name: String, val clazz: KClass<*>) class Context(val coreContext: CoreContext) { ... } abstract class Module(){ lateinit var coreContext: CoreContext abstract fun context() : Context fun declareContext(init: Context.() -> Unit) = Context(coreContext).apply(init) } class CoreContext{ var instances = HashMap,Any>() var definitions = listOf>() }

Slide 81

Slide 81 text

class Context(val coreContext: CoreContext) { //... inline fun get() : T = instances[T::class] }

Slide 82

Slide 82 text

class Context(val coreContext: CoreContext) { //... inline fun get() : T = coreContext.inject() }

Slide 83

Slide 83 text

class CoreContext { var instances = HashMap, Any>() var definitions = listOf>() fun inject(): T {} }

Slide 84

Slide 84 text

class CoreContext { var instances = HashMap, Any>() var definitions = listOf>() fun inject(): T { val clazz = T::class } }

Slide 85

Slide 85 text

class CoreContext { var instances = HashMap, Any>() var definitions = listOf>() inline fun inject(): T { val clazz = T::class } }

Slide 86

Slide 86 text

class CoreContext { var instances = HashMap, Any>() var definitions = listOf>() inline fun inject(): T { val clazz = T::class // found one ? val foundInstance: T? = instances[clazz] as? T } }

Slide 87

Slide 87 text

class CoreContext { var instances = HashMap, Any>() var definitions = listOf>() inline fun inject(): T { val clazz = T::class // found one ? val foundInstance: T? = instances[clazz] as? T // create one ? val createdInstance: T? = if (foundInstance == null) { definitions.firstOrNull { it.clazz == clazz }?.let { it.definition.invoke() as? T? } } else null } }

Slide 88

Slide 88 text

class CoreContext { var instances = HashMap, Any>() var definitions = listOf>() inline fun inject(): T { val clazz = T::class // found one ? val foundInstance: T? = instances[clazz] as? T // create one ? val createdInstance: T? = if (foundInstance == null) { definitions.firstOrNull { it.clazz == clazz }?.let { it.definition.invoke() as? T? } } else null } }

Slide 89

Slide 89 text

class CoreContext { var instances = HashMap, Any>() var definitions = listOf>() inline fun inject(): T { val clazz = T::class // found one ? val foundInstance: T? = instances[clazz] as? T // create one ? val createdInstance: T? = if (foundInstance == null) { definitions.firstOrNull { it.clazz == clazz }?.let { it.definition.invoke() as? T? } } else null } }

Slide 90

Slide 90 text

class CoreContext { var instances = HashMap, Any>() var definitions = listOf>() inline fun inject(): T { val clazz = T::class // found one ? val foundInstance: T? = instances[clazz] as? T // create one ? val createdInstance: T? = if (foundInstance == null) { definitions.firstOrNull { it.clazz == clazz }?.let { it.definition.invoke() as? T? } } else null } }

Slide 91

Slide 91 text

class CoreContext { var instances = HashMap, Any>() var definitions = listOf>() inline fun inject(): T { val clazz = T::class // found one ? val foundInstance: T? = instances[clazz] as? T // create one ? val createdInstance: T? = if (foundInstance == null) { definitions.firstOrNull { it.clazz == clazz }?.let { it.definition.invoke() as? T? } } else null // Got it val instance: T = (foundInstance ?: createdInstance) ?: error("Bean $clazz not found") } }

Slide 92

Slide 92 text

class CoreContext { var instances = HashMap, Any>() var definitions = listOf>() inline fun inject(): T { val clazz = T::class // found one ? val foundInstance: T? = instances[clazz] as? T // create one ? val createdInstance: T? = if (foundInstance == null) { definitions.firstOrNull { it.clazz == clazz }?.let { it.definition.invoke() as? T? } } else null // Got it val instance: T = (foundInstance ?: createdInstance) ?: error("Bean $clazz not found ») // Save it if (createdInstance != null && foundInstance == null) { instances[clazz] = createdInstance as Any } } }

Slide 93

Slide 93 text

class CoreContext { var instances = HashMap, Any>() var definitions = listOf>() inline fun inject(): T { val clazz = T::class // found one ? val foundInstance: T? = instances[clazz] as? T // create one ? val createdInstance: T? = if (foundInstance == null) { definitions.firstOrNull { it.clazz == clazz }?.let { it.definition.invoke() as? T? } } else null // Got it val instance: T = (foundInstance ?: createdInstance) ?: error("Bean $clazz not found") // Save it if (createdInstance != null && foundInstance == null) { instances[clazz] = createdInstance as Any } return instance } }

Slide 94

Slide 94 text

class CoreContext { var instances = HashMap, Any>() var definitions = listOf>() fun build(module: T) {} inline fun inject(): T {} }

Slide 95

Slide 95 text

class CoreContext { var instances = HashMap, Any>() var definitions = listOf>() fun build(module: T) { module.coreContext = this } inline fun inject(): T {} }

Slide 96

Slide 96 text

class CoreContext { var instances = HashMap, Any>() var definitions = listOf>() fun build(module: T) { module.coreContext = this definitions += module.context().definitions } inline fun inject(): T {} }

Slide 97

Slide 97 text

data class MyServiceA() data class MyServiceB(val a : MyServiceA) data class MyServiceC(val a : MyServiceA, val b : MyServiceB) class SimpleModule : Module() { override fun context() = declareContext { provide { ServiceA() } provide { ServiceB(get()) } provide { ServiceC(get(), get()) } } } Let’s use it

Slide 98

Slide 98 text

val ctx = CoreContext() ctx.build(SimpleModule()) data class MyServiceA() data class MyServiceB(val a : MyServiceA) data class MyServiceC(val a : MyServiceA, val b : MyServiceB) class SimpleModule : Module() { override fun context() = declareContext { provide { ServiceA() } provide { ServiceB(get()) } provide { ServiceC(get(), get()) } } }

Slide 99

Slide 99 text

val ctx = CoreContext() ctx.build(SimpleModule()) val serviceB = ctx.inject() data class MyServiceA() data class MyServiceB(val a : MyServiceA) data class MyServiceC(val a : MyServiceA, val b : MyServiceB) class SimpleModule : Module() { override fun context() = declareContext { provide { ServiceA() } provide { ServiceB(get()) } provide { ServiceC(get(), get()) } } }

Slide 100

Slide 100 text

No code generation No annotation No introspection No proxy

Slide 101

Slide 101 text

Reflection -> Kclass, KProperty, KFunction … -> Java => Extra lib And also … Extra Binding Lazy Inject

Slide 102

Slide 102 text

No content

Slide 103

Slide 103 text

https:/ /github.com/Ekito/koin

Slide 104

Slide 104 text

Collections & Concurrency

Slide 105

Slide 105 text

Collections

Slide 106

Slide 106 text

KEEP immutable collections - « real » immutable collections - avoid java backed collections New in 1.1 - Array-Like instantiation - onEach() - minOf/maxOf - groupingBy() - Map : minus(), getValue() Collections

Slide 107

Slide 107 text

Stream API (Kotlin on Java 8+) - toStream() Collection to Sequences (Pure Kotlin or Java 6/7) - asSequence() Lazy Collections

Slide 108

Slide 108 text

sequence.map {…} .filter {…} .toList() Intermediate operations terminal operation sequence.map {…} .filter {…} .toList() sequence.map {…} .filter {…} .toList()

Slide 109

Slide 109 text

Async Programming

Slide 110

Slide 110 text

⚠ Experimental feature ⚠

Slide 111

Slide 111 text

kotlinx.coroutines

Slide 112

Slide 112 text

Kotlin >= 1.1.4 Gradle: compile ‘org.jetbrains.kotlinx:kotlinx-coroutines-core:0.18’ Remove warnings: kotlin { experimental { coroutines "enable" } }

Slide 113

Slide 113 text

Suspend - keyword, mark function as « suspending function » Coroutines - API for computations that can be suspended without blocking a thread - launched with coroutine builder (light-weight threads)

Slide 114

Slide 114 text

WELCOME TO THE ASYNC WORLD

Slide 115

Slide 115 text

@Test fun test() = runBlocking { val jobs = List(100_000) { launch(CommonPool) { delay(1000L) print(".") } } jobs.forEach { it.join() } }

Slide 116

Slide 116 text

@Test fun test() = runBlocking { val jobs = List(100_000) { launch(CommonPool) { delay(1000L) print(".") } } jobs.forEach { it.join() } } @Test fun test() = runBlocking { val jobs = List(100_000) { launch(CommonPool) { delay(1000L) print(".") } } jobs.forEach { it.join() } }

Slide 117

Slide 117 text

@Test fun test() = runBlocking { val jobs = List(100_000) { launch(CommonPool) { delay(1000L) print(".") } } jobs.forEach { it.join() } } @Test fun test() = runBlocking { val jobs = List(100_000) { launch(CommonPool) { delay(1000L) print(".") } } jobs.forEach { it.join() } } @Test fun test() = runBlocking { val jobs = List(100_000) { launch(CommonPool) { delay(1000L) print(".") } } jobs.forEach { it.join() } }

Slide 118

Slide 118 text

@Test fun test() = runBlocking { val jobs = List(100_000) { launch(CommonPool) { delay(1000L) print(".") } } jobs.forEach { it.join() } } @Test fun test() = runBlocking { val jobs = List(100_000) { launch(CommonPool) { delay(1000L) print(".") } } jobs.forEach { it.join() } } @Test fun test() = runBlocking { val jobs = List(100_000) { launch(CommonPool) { delay(1000L) print(".") } } jobs.forEach { it.join() } } @Test fun test() = runBlocking { val jobs = List(100_000) { launch(CommonPool) { delay(1000L) print(".") } } jobs.forEach { it.join() } }

Slide 119

Slide 119 text

@Test fun test() = runBlocking { val jobs = List(100_000) { launch(CommonPool) { delay(1000L) print(".") } } jobs.forEach { it.join() } } @Test fun test() = runBlocking { val jobs = List(100_000) { launch(CommonPool) { delay(1000L) print(".") } } jobs.forEach { it.join() } } @Test fun test() = runBlocking { val jobs = List(100_000) { launch(CommonPool) { delay(1000L) print(".") } } jobs.forEach { it.join() } } @Test fun test() = runBlocking { val jobs = List(100_000) { launch(CommonPool) { delay(1000L) print(".") } } jobs.forEach { it.join() } } @Test fun test() = runBlocking { val jobs = List(100_000) { launch(CommonPool) { delay(1000L) print(".") } } jobs.forEach { it.join() } }

Slide 120

Slide 120 text

@Test fun test() = runBlocking { val jobs = List(100_000) { launch(CommonPool) { delay(1000L) print(".") } } jobs.forEach { it.join() } } @Test fun test() = runBlocking { val jobs = List(100_000) { launch(CommonPool) { delay(1000L) print(".") } } jobs.forEach { it.join() } } @Test fun test() = runBlocking { val jobs = List(100_000) { launch(CommonPool) { delay(1000L) print(".") } } jobs.forEach { it.join() } } @Test fun test() = runBlocking { val jobs = List(100_000) { launch(CommonPool) { delay(1000L) print(".") } } jobs.forEach { it.join() } } @Test fun test() = runBlocking { val jobs = List(100_000) { launch(CommonPool) { delay(1000L) print(".") } } jobs.forEach { it.join() } } @Test fun test() = runBlocking { val main = measureTimeMillis { val jobs = List(100_000) { launch(CommonPool) { delay(1000L) print(".") } } jobs.forEach { it.join() } } println("\ndone in $main") }

Slide 121

Slide 121 text

@Test fun test() = runBlocking { val main = measureTimeMillis { val jobs = List(100_000) { launch(CommonPool) { doSomething() } } jobs.forEach { it.join() } } println("\ndone in $main") } suspend fun doSomething() { delay(1000L) print(".") }

Slide 122

Slide 122 text

suspend fun delay(time: Long, unit: TimeUnit = TimeUnit.MILLISECONDS) {…} suspend fun delay(time: Long, unit: TimeUnit = TimeUnit.MILLISECONDS) public fun runBlocking(context: CoroutineContext = EmptyCoroutineContext, block: suspend CoroutineScope.() -> T): T {…}

Slide 123

Slide 123 text

Kotlin coroutines ~ 1s Java ForkJoin ~ 15s

Slide 124

Slide 124 text

Dispatching jobs

Slide 125

Slide 125 text

@Test
 fun testWeather() = runBlocking {
 log("starting ...")
 val ws = retrofitWS("https://weather-api.herokuapp.com/")
 try {
 val location = asyncGeocode(ws).await() ?: error("No location :(")
 val weather = asyncWeather(location, ws).await()
 log("got weather : $weather")
 } catch (e: Exception) {
 System.err.println("Error is $e")
 }
 log("finished !")
 }
 
 private fun asyncWeather(location: Location, ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get weather for $location")
 ws.weather(location.lat, location.lng, "EN").execute().body()
 }
 
 private fun asyncGeocode(ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get location")
 ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 }

Slide 126

Slide 126 text

@Test
 fun testWeather() = runBlocking {
 log("starting ...")
 val ws = retrofitWS("https://weather-api.herokuapp.com/")
 try {
 val location = asyncGeocode(ws).await() ?: error("No location :(")
 val weather = asyncWeather(location, ws).await()
 log("got weather : $weather")
 } catch (e: Exception) {
 System.err.println("Error is $e")
 }
 log("finished !")
 }
 
 private fun asyncWeather(location: Location, ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get weather for $location")
 ws.weather(location.lat, location.lng, "EN").execute().body()
 }
 
 private fun asyncGeocode(ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get location")
 ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 } @Test
 fun testWeather() = runBlocking {
 log("starting ...")
 val ws = retrofitWS("https://weather-api.herokuapp.com/")
 try {
 val location = asyncGeocode(ws).await() ?: error("No location :(")
 val weather = asyncWeather(location, ws).await()
 log("got weather : $weather")
 } catch (e: Exception) {
 System.err.println("Error is $e")
 }
 log("finished !")
 }
 
 private fun asyncWeather(location: Location, ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get weather for $location")
 ws.weather(location.lat, location.lng, "EN").execute().body()
 }
 
 private fun asyncGeocode(ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get location")
 ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 }

Slide 127

Slide 127 text

@Test
 fun testWeather() = runBlocking {
 log("starting ...")
 val ws = retrofitWS("https://weather-api.herokuapp.com/")
 try {
 val location = asyncGeocode(ws).await() ?: error("No location :(")
 val weather = asyncWeather(location, ws).await()
 log("got weather : $weather")
 } catch (e: Exception) {
 System.err.println("Error is $e")
 }
 log("finished !")
 }
 
 private fun asyncWeather(location: Location, ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get weather for $location")
 ws.weather(location.lat, location.lng, "EN").execute().body()
 }
 
 private fun asyncGeocode(ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get location")
 ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 } @Test
 fun testWeather() = runBlocking {
 log("starting ...")
 val ws = retrofitWS("https://weather-api.herokuapp.com/")
 try {
 val location = asyncGeocode(ws).await() ?: error("No location :(")
 val weather = asyncWeather(location, ws).await()
 log("got weather : $weather")
 } catch (e: Exception) {
 System.err.println("Error is $e")
 }
 log("finished !")
 }
 
 private fun asyncWeather(location: Location, ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get weather for $location")
 ws.weather(location.lat, location.lng, "EN").execute().body()
 }
 
 private fun asyncGeocode(ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get location")
 ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 } @Test
 fun testWeather() = runBlocking {
 log("starting ...")
 val ws = retrofitWS("https://weather-api.herokuapp.com/")
 try {
 val location = asyncGeocode(ws).await() ?: error("No location :(")
 val weather = asyncWeather(location, ws).await()
 log("got weather : $weather")
 } catch (e: Exception) {
 System.err.println("Error is $e")
 }
 log("finished !")
 }
 
 private fun asyncWeather(location: Location, ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get weather for $location")
 ws.weather(location.lat, location.lng, "EN").execute().body()
 }
 
 private fun asyncGeocode(ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get location")
 ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 }

Slide 128

Slide 128 text

@Test
 fun testWeather() = runBlocking {
 log("starting ...")
 val ws = retrofitWS("https://weather-api.herokuapp.com/")
 try {
 val location = asyncGeocode(ws).await() ?: error("No location :(")
 val weather = asyncWeather(location, ws).await()
 log("got weather : $weather")
 } catch (e: Exception) {
 System.err.println("Error is $e")
 }
 log("finished !")
 }
 
 private fun asyncWeather(location: Location, ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get weather for $location")
 ws.weather(location.lat, location.lng, "EN").execute().body()
 }
 
 private fun asyncGeocode(ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get location")
 ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 } @Test
 fun testWeather() = runBlocking {
 log("starting ...")
 val ws = retrofitWS("https://weather-api.herokuapp.com/")
 try {
 val location = asyncGeocode(ws).await() ?: error("No location :(")
 val weather = asyncWeather(location, ws).await()
 log("got weather : $weather")
 } catch (e: Exception) {
 System.err.println("Error is $e")
 }
 log("finished !")
 }
 
 private fun asyncWeather(location: Location, ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get weather for $location")
 ws.weather(location.lat, location.lng, "EN").execute().body()
 }
 
 private fun asyncGeocode(ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get location")
 ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 } @Test
 fun testWeather() = runBlocking {
 log("starting ...")
 val ws = retrofitWS("https://weather-api.herokuapp.com/")
 try {
 val location = asyncGeocode(ws).await() ?: error("No location :(")
 val weather = asyncWeather(location, ws).await()
 log("got weather : $weather")
 } catch (e: Exception) {
 System.err.println("Error is $e")
 }
 log("finished !")
 }
 
 private fun asyncWeather(location: Location, ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get weather for $location")
 ws.weather(location.lat, location.lng, "EN").execute().body()
 }
 
 private fun asyncGeocode(ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get location")
 ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 } @Test
 fun testWeather() = runBlocking {
 log("starting ...")
 val ws = retrofitWS("https://weather-api.herokuapp.com/")
 try {
 val location = asyncGeocode(ws).await() ?: error("No location :(")
 val weather = asyncWeather(location, ws).await()
 log("got weather : $weather")
 } catch (e: Exception) {
 System.err.println("Error is $e")
 }
 log("finished !")
 }
 
 private fun asyncWeather(location: Location, ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get weather for $location")
 ws.weather(location.lat, location.lng, "EN").execute().body()
 }
 
 private fun asyncGeocode(ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get location")
 ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 }

Slide 129

Slide 129 text

@Test
 fun testWeather() = runBlocking {
 log("starting ...")
 val ws = retrofitWS("https://weather-api.herokuapp.com/")
 try {
 val location = asyncGeocode(ws).await() ?: error("No location :(")
 val weather = asyncWeather(location, ws).await()
 log("got weather : $weather")
 } catch (e: Exception) {
 System.err.println("Error is $e")
 }
 log("finished !")
 }
 
 private fun asyncWeather(location: Location, ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get weather for $location")
 ws.weather(location.lat, location.lng, "EN").execute().body()
 }
 
 private fun asyncGeocode(ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get location")
 ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 } @Test
 fun testWeather() = runBlocking {
 log("starting ...")
 val ws = retrofitWS("https://weather-api.herokuapp.com/")
 try {
 val location = asyncGeocode(ws).await() ?: error("No location :(")
 val weather = asyncWeather(location, ws).await()
 log("got weather : $weather")
 } catch (e: Exception) {
 System.err.println("Error is $e")
 }
 log("finished !")
 }
 
 private fun asyncWeather(location: Location, ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get weather for $location")
 ws.weather(location.lat, location.lng, "EN").execute().body()
 }
 
 private fun asyncGeocode(ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get location")
 ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 } @Test
 fun testWeather() = runBlocking {
 log("starting ...")
 val ws = retrofitWS("https://weather-api.herokuapp.com/")
 try {
 val location = asyncGeocode(ws).await() ?: error("No location :(")
 val weather = asyncWeather(location, ws).await()
 log("got weather : $weather")
 } catch (e: Exception) {
 System.err.println("Error is $e")
 }
 log("finished !")
 }
 
 private fun asyncWeather(location: Location, ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get weather for $location")
 ws.weather(location.lat, location.lng, "EN").execute().body()
 }
 
 private fun asyncGeocode(ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get location")
 ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 } @Test
 fun testWeather() = runBlocking {
 log("starting ...")
 val ws = retrofitWS("https://weather-api.herokuapp.com/")
 try {
 val location = asyncGeocode(ws).await() ?: error("No location :(")
 val weather = asyncWeather(location, ws).await()
 log("got weather : $weather")
 } catch (e: Exception) {
 System.err.println("Error is $e")
 }
 log("finished !")
 }
 
 private fun asyncWeather(location: Location, ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get weather for $location")
 ws.weather(location.lat, location.lng, "EN").execute().body()
 }
 
 private fun asyncGeocode(ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get location")
 ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 } @Test
 fun testWeather() = runBlocking {
 log("starting ...")
 val ws = retrofitWS("https://weather-api.herokuapp.com/")
 try {
 val location = asyncGeocode(ws).await() ?: error("No location :(")
 val weather = asyncWeather(location, ws).await()
 log("got weather : $weather")
 } catch (e: Exception) {
 System.err.println("Error is $e")
 }
 log("finished !")
 }
 
 private fun asyncWeather(location: Location, ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get weather for $location")
 ws.weather(location.lat, location.lng, "EN").execute().body()
 }
 
 private fun asyncGeocode(ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get location")
 ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 }

Slide 130

Slide 130 text

@Test
 fun testWeather() = runBlocking {
 log("starting ...")
 val ws = retrofitWS("https://weather-api.herokuapp.com/")
 try {
 val location = asyncGeocode(ws).await() ?: error("No location :(")
 val weather = asyncWeather(location, ws).await()
 log("got weather : $weather")
 } catch (e: Exception) {
 System.err.println("Error is $e")
 }
 log("finished !")
 }
 
 private fun asyncWeather(location: Location, ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get weather for $location")
 ws.weather(location.lat, location.lng, "EN").execute().body()
 }
 
 private fun asyncGeocode(ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get location")
 ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 }

Slide 131

Slide 131 text

@Test
 fun testWeather() = runBlocking {
 log("starting ...")
 val ws = retrofitWS("https://weather-api.herokuapp.com/")
 try {
 val location = asyncGeocode(ws).await() ?: error("No location :(")
 val weather = asyncWeather(location, ws).await()
 log("got weather : $weather")
 } catch (e: Exception) {
 System.err.println("Error is $e")
 }
 log("finished !")
 }
 
 private fun asyncWeather(location: Location, ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get weather for $location")
 ws.weather(location.lat, location.lng, "EN").execute().body()
 }
 
 private fun asyncGeocode(ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get location")
 ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 } @Test
 fun testWeather() = runBlocking {
 log("starting ...")
 val ws = retrofitWS("https://weather-api.herokuapp.com/")
 try {
 val location = asyncGeocode(ws).await() ?: error("No location :(")
 val weather = asyncWeather(location, ws).await()
 log("got weather : $weather")
 } catch (e: Exception) {
 System.err.println("Error is $e")
 }
 log("finished !")
 }
 
 private fun asyncWeather(location: Location, ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get weather for $location")
 ws.weather(location.lat, location.lng, "EN").execute().body()
 }
 
 private fun asyncGeocode(ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get location")
 ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 }

Slide 132

Slide 132 text

@Test
 fun testWeather() = runBlocking {
 log("starting ...")
 val ws = retrofitWS("https://weather-api.herokuapp.com/")
 try {
 val location = asyncGeocode(ws).await() ?: error("No location :(")
 val weather = asyncWeather(location, ws).await()
 log("got weather : $weather")
 } catch (e: Exception) {
 System.err.println("Error is $e")
 }
 log("finished !")
 }
 
 private fun asyncWeather(location: Location, ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get weather for $location")
 ws.weather(location.lat, location.lng, "EN").execute().body()
 }
 
 private fun asyncGeocode(ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get location")
 ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 } @Test
 fun testWeather() = runBlocking {
 log("starting ...")
 val ws = retrofitWS("https://weather-api.herokuapp.com/")
 try {
 val location = asyncGeocode(ws).await() ?: error("No location :(")
 val weather = asyncWeather(location, ws).await()
 log("got weather : $weather")
 } catch (e: Exception) {
 System.err.println("Error is $e")
 }
 log("finished !")
 }
 
 private fun asyncWeather(location: Location, ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get weather for $location")
 ws.weather(location.lat, location.lng, "EN").execute().body()
 }
 
 private fun asyncGeocode(ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get location")
 ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 } @Test
 fun testWeather() = runBlocking {
 log("starting ...")
 val ws = retrofitWS("https://weather-api.herokuapp.com/")
 try {
 val location = asyncGeocode(ws).await() ?: error("No location :(")
 val weather = asyncWeather(location, ws).await()
 log("got weather : $weather")
 } catch (e: Exception) {
 System.err.println("Error is $e")
 }
 log("finished !")
 }
 
 private fun asyncWeather(location: Location, ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get weather for $location")
 ws.weather(location.lat, location.lng, "EN").execute().body()
 }
 
 private fun asyncGeocode(ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get location")
 ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 }

Slide 133

Slide 133 text

@Test
 fun testWeather() = runBlocking {
 log("starting ...")
 val ws = retrofitWS("https://weather-api.herokuapp.com/")
 try {
 val location = asyncGeocode(ws).await() ?: error("No location :(")
 val weather = asyncWeather(location, ws).await()
 log("got weather : $weather")
 } catch (e: Exception) {
 System.err.println("Error is $e")
 }
 log("finished !")
 }
 
 private fun asyncWeather(location: Location, ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get weather for $location")
 ws.weather(location.lat, location.lng, "EN").execute().body()
 }
 
 private fun asyncGeocode(ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get location")
 ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 } @Test
 fun testWeather() = runBlocking {
 log("starting ...")
 val ws = retrofitWS("https://weather-api.herokuapp.com/")
 try {
 val location = asyncGeocode(ws).await() ?: error("No location :(")
 val weather = asyncWeather(location, ws).await()
 log("got weather : $weather")
 } catch (e: Exception) {
 System.err.println("Error is $e")
 }
 log("finished !")
 }
 
 private fun asyncWeather(location: Location, ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get weather for $location")
 ws.weather(location.lat, location.lng, "EN").execute().body()
 }
 
 private fun asyncGeocode(ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get location")
 ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 } @Test
 fun testWeather() = runBlocking {
 log("starting ...")
 val ws = retrofitWS("https://weather-api.herokuapp.com/")
 try {
 val location = asyncGeocode(ws).await() ?: error("No location :(")
 val weather = asyncWeather(location, ws).await()
 log("got weather : $weather")
 } catch (e: Exception) {
 System.err.println("Error is $e")
 }
 log("finished !")
 }
 
 private fun asyncWeather(location: Location, ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get weather for $location")
 ws.weather(location.lat, location.lng, "EN").execute().body()
 }
 
 private fun asyncGeocode(ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get location")
 ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 } @Test
 fun testWeather() = runBlocking {
 log("starting ...")
 val ws = retrofitWS("https://weather-api.herokuapp.com/")
 try {
 val location = asyncGeocode(ws).await() ?: error("No location :(")
 val weather = asyncWeather(location, ws).await()
 log("got weather : $weather")
 } catch (e: Exception) {
 System.err.println("Error is $e")
 }
 log("finished !")
 }
 
 private fun asyncWeather(location: Location, ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get weather for $location")
 ws.weather(location.lat, location.lng, "EN").execute().body()
 }
 
 private fun asyncGeocode(ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get location")
 ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 }

Slide 134

Slide 134 text

@Test
 fun testWeather() = runBlocking {
 log("starting ...")
 val ws = retrofitWS("https://weather-api.herokuapp.com/")
 try {
 val location = asyncGeocode(ws).await() ?: error("No location :(")
 val weather = asyncWeather(location, ws).await()
 log("got weather : $weather")
 } catch (e: Exception) {
 System.err.println("Error is $e")
 }
 log("finished !")
 }
 
 private fun asyncWeather(location: Location, ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get weather for $location")
 ws.weather(location.lat, location.lng, "EN").execute().body()
 }
 
 private fun asyncGeocode(ws: BlockingWeatherWS): Deferred = async(CommonPool) {
 log("get location")
 ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 }

Slide 135

Slide 135 text

Data streaming with channels

Slide 136

Slide 136 text

@Test
 fun testWeather() = runBlocking {
 val ws = retrofitWS("https://my-weather-api.herokuapp.com/")
 val time = measureTimeMillis {
 val location = channelLocation(ws)
 val weather = channelWeather(location, ws)
 weather.consumeEach { w ->
 log("got weather : $w")
 }
 location.cancel()
 weather.cancel()
 }
 log("\ndone in $time")
 }
 
 private fun channelWeather(locationChannel: ProducerJob, ws: BlockingWeatherWS) = produce(CommonPool) {
 log("get weather for $locationChannel")
 locationChannel.consumeEach { location ->
 val list = ws.weather(location.lat, location.lng, "EN").execute().body().forecast?.simpleforecast?.forecastday?.take(4).orEmpty()
 list.forEach { send(it) }
 }
 }
 
 private fun channelLocation(ws: BlockingWeatherWS) = produce(CommonPool) {
 log("get location")
 val location = ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 location?.let {
 send(location)
 }
 }

Slide 137

Slide 137 text

@Test
 fun testWeather() = runBlocking {
 val ws = retrofitWS("https://my-weather-api.herokuapp.com/")
 val time = measureTimeMillis {
 val location = channelLocation(ws)
 val weather = channelWeather(location, ws)
 weather.consumeEach { w ->
 log("got weather : $w")
 }
 location.cancel()
 weather.cancel()
 }
 log("\ndone in $time")
 }
 
 private fun channelWeather(locationChannel: ProducerJob, ws: BlockingWeatherWS) = produce(CommonPool) {
 log("get weather for $locationChannel")
 locationChannel.consumeEach { location ->
 val list = ws.weather(location.lat, location.lng, "EN").execute().body().forecast?.simpleforecast?.forecastday?.take(4).orEmpty()
 list.forEach { send(it) }
 }
 }
 
 private fun channelLocation(ws: BlockingWeatherWS) = produce(CommonPool) {
 log("get location")
 val location = ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 location?.let {
 send(location)
 }
 }

Slide 138

Slide 138 text

@Test
 fun testWeather() = runBlocking {
 val ws = retrofitWS("https://my-weather-api.herokuapp.com/")
 val time = measureTimeMillis {
 val location = channelLocation(ws)
 val weather = channelWeather(location, ws)
 weather.consumeEach { w ->
 log("got weather : $w")
 }
 location.cancel()
 weather.cancel()
 }
 log("\ndone in $time")
 }
 
 private fun channelWeather(locationChannel: ProducerJob, ws: BlockingWeatherWS) = produce(CommonPool) {
 log("get weather for $locationChannel")
 locationChannel.consumeEach { location ->
 val list = ws.weather(location.lat, location.lng, "EN").execute().body().forecast?.simpleforecast?.forecastday?.take(4).orEmpty()
 list.forEach { send(it) }
 }
 }
 
 private fun channelLocation(ws: BlockingWeatherWS) = produce(CommonPool) {
 log("get location")
 val location = ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 location?.let {
 send(location)
 }
 }

Slide 139

Slide 139 text

@Test
 fun testWeather() = runBlocking {
 val ws = retrofitWS("https://my-weather-api.herokuapp.com/")
 val time = measureTimeMillis {
 val location = channelLocation(ws)
 val weather = channelWeather(location, ws)
 weather.consumeEach { w ->
 log("got weather : $w")
 }
 location.cancel()
 weather.cancel()
 }
 log("\ndone in $time")
 }
 
 private fun channelWeather(locationChannel: ProducerJob, ws: BlockingWeatherWS) = produce(CommonPool) {
 log("get weather for $locationChannel")
 locationChannel.consumeEach { location ->
 val list = ws.weather(location.lat, location.lng, "EN").execute().body().forecast?.simpleforecast?.forecastday?.take(4).orEmpty()
 list.forEach { send(it) }
 }
 }
 
 private fun channelLocation(ws: BlockingWeatherWS) = produce(CommonPool) {
 log("get location")
 val location = ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 location?.let {
 send(location)
 }
 }

Slide 140

Slide 140 text

@Test
 fun testWeather() = runBlocking {
 val ws = retrofitWS("https://my-weather-api.herokuapp.com/")
 val time = measureTimeMillis {
 val location = channelLocation(ws)
 val weather = channelWeather(location, ws)
 weather.consumeEach { w ->
 log("got weather : $w")
 }
 location.cancel()
 weather.cancel()
 }
 log("\ndone in $time")
 }
 
 private fun channelWeather(locationChannel: ProducerJob, ws: BlockingWeatherWS) = produce(CommonPool) {
 log("get weather for $locationChannel")
 locationChannel.consumeEach { location ->
 val list = ws.weather(location.lat, location.lng, "EN").execute().body().forecast?.simpleforecast?.forecastday?.take(4).orEmpty()
 list.forEach { send(it) }
 }
 }
 
 private fun channelLocation(ws: BlockingWeatherWS) = produce(CommonPool) {
 log("get location")
 val location = ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 location?.let {
 send(location)
 }
 }

Slide 141

Slide 141 text

@Test
 fun testWeather() = runBlocking {
 val ws = retrofitWS("https://my-weather-api.herokuapp.com/")
 val time = measureTimeMillis {
 val location = channelLocation(ws)
 val weather = channelWeather(location, ws)
 weather.consumeEach { w ->
 log("got weather : $w")
 }
 location.cancel()
 weather.cancel()
 }
 log("\ndone in $time")
 }
 
 private fun channelWeather(locationChannel: ProducerJob, ws: BlockingWeatherWS) = produce(CommonPool) {
 log("get weather for $locationChannel")
 locationChannel.consumeEach { location ->
 val list = ws.weather(location.lat, location.lng, "EN").execute().body().forecast?.simpleforecast?.forecastday?.take(4).orEmpty()
 list.forEach { send(it) }
 }
 }
 
 private fun channelLocation(ws: BlockingWeatherWS) = produce(CommonPool) {
 log("get location")
 val location = ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 location?.let {
 send(location)
 }
 }

Slide 142

Slide 142 text

@Test
 fun testWeather() = runBlocking {
 val ws = retrofitWS("https://my-weather-api.herokuapp.com/")
 val time = measureTimeMillis {
 val location = channelLocation(ws)
 val weather = channelWeather(location, ws)
 weather.consumeEach { w ->
 log("got weather : $w")
 }
 location.cancel()
 weather.cancel()
 }
 log("\ndone in $time")
 }
 
 private fun channelWeather(locationChannel: ProducerJob, ws: BlockingWeatherWS) = produce(CommonPool) {
 log("get weather for $locationChannel")
 locationChannel.consumeEach { location ->
 val list = ws.weather(location.lat, location.lng, "EN").execute().body().forecast?.simpleforecast?.forecastday?.take(4).orEmpty()
 list.forEach { send(it) }
 }
 }
 
 private fun channelLocation(ws: BlockingWeatherWS) = produce(CommonPool) {
 log("get location")
 val location = ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 location?.let {
 send(location)
 }
 }

Slide 143

Slide 143 text

@Test
 fun testWeather() = runBlocking {
 val ws = retrofitWS("https://my-weather-api.herokuapp.com/")
 val time = measureTimeMillis {
 val location = channelLocation(ws)
 val weather = channelWeather(location, ws)
 weather.consumeEach { w ->
 log("got weather : $w")
 }
 location.cancel()
 weather.cancel()
 }
 log("\ndone in $time")
 }
 
 private fun channelWeather(locationChannel: ProducerJob, ws: BlockingWeatherWS) = produce(CommonPool) {
 log("get weather for $locationChannel")
 locationChannel.consumeEach { location ->
 val list = ws.weather(location.lat, location.lng, "EN").execute().body().forecast?.simpleforecast?.forecastday?.take(4).orEmpty()
 list.forEach { send(it) }
 }
 }
 
 private fun channelLocation(ws: BlockingWeatherWS) = produce(CommonPool) {
 log("get location")
 val location = ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 location?.let {
 send(location)
 }
 }

Slide 144

Slide 144 text

@Test
 fun testWeather() = runBlocking {
 val ws = retrofitWS("https://my-weather-api.herokuapp.com/")
 val time = measureTimeMillis {
 val location = channelLocation(ws)
 val weather = channelWeather(location, ws)
 weather.consumeEach { w ->
 log("got weather : $w")
 }
 location.cancel()
 weather.cancel()
 }
 log("\ndone in $time")
 }
 
 private fun channelWeather(locationChannel: ProducerJob, ws: BlockingWeatherWS) = produce(CommonPool) {
 log("get weather for $locationChannel")
 locationChannel.consumeEach { location ->
 val list = ws.weather(location.lat, location.lng, "EN").execute().body().forecast?.simpleforecast?.forecastday?.take(4).orEmpty()
 list.forEach { send(it) }
 }
 }
 
 private fun channelLocation(ws: BlockingWeatherWS) = produce(CommonPool) {
 log("get location")
 val location = ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 location?.let {
 send(location)
 }
 }

Slide 145

Slide 145 text

@Test
 fun testWeather() = runBlocking {
 val ws = retrofitWS("https://my-weather-api.herokuapp.com/")
 val time = measureTimeMillis {
 val location = channelLocation(ws)
 val weather = channelWeather(location, ws)
 weather.consumeEach { w ->
 log("got weather : $w")
 }
 location.cancel()
 weather.cancel()
 }
 log("\ndone in $time")
 }
 
 private fun channelWeather(locationChannel: ProducerJob, ws: BlockingWeatherWS) = produce(CommonPool) {
 log("get weather for $locationChannel")
 locationChannel.consumeEach { location ->
 val list = ws.weather(location.lat, location.lng, "EN").execute().body().forecast?.simpleforecast?.forecastday?.take(4).orEmpty()
 list.forEach { send(it) }
 }
 }
 
 private fun channelLocation(ws: BlockingWeatherWS) = produce(CommonPool) {
 log("get location")
 val location = ws.geocode("Toulouse,fr").execute().body().results.first().geometry?.location
 location?.let {
 send(location)
 }
 }

Slide 146

Slide 146 text

Coroutines - builder (runBlocking, async, launch …) - primitives (delay, measureTime, job…) - communication (deferred, channel, selector, actor …) => Reactive world (RxJava …) => UI (JavaFX, Android …) => Testing (?)

Slide 147

Slide 147 text

Further reading https:/ /github.com/Kotlin/kotlinx.coroutines/blob/master/coroutines-guide.md https:/ /github.com/Kotlin/kotlinx.coroutines/blob/master/ui/coroutines-guide-ui.md https:/ /github.com/Kotlin/anko/wiki/Anko-Coroutines https:/ /akarnokd.blogspot.fr/2017/09/rxjava-vs-kotlin-coroutines-quick-look.html?m=1 https:/ /github.com/Kotlin/kotlinx.coroutines/blob/master/reactive/coroutines- guide-reactive.md Coroutines vs RxJava

Slide 148

Slide 148 text

Beyond Kotlin Playground https:/ /github.com/Ekito/beyond-kotlin-playground

Slide 149

Slide 149 text

What’s next?

Slide 150

Slide 150 text

On the road to Kotlin 1.2 https:/ /blog.jetbrains.com/kotlin/2017/08/kotlin-1-2-m2-is-out/ https:/ /blog.jetbrains.com/kotlin/2017/06/early-access-program-for- kotlin-1-2-has-been-started/

Slide 151

Slide 151 text

Others stuffs in 1.1 https:/ /kotlinlang.org/docs/reference/whatsnew11.html Gradle Kotlin Scripts https:/ /github.com/gradle/kotlin-dsl Kotlin Native https:/ /github.com/JetBrains/kotlin-native

Slide 152

Slide 152 text

Thank you :)