kotlin, smarter development for the jvm

65
Smarter development for the JVM #GeekBreakFast Kotlin

Upload: arnaud-giuliani

Post on 11-Jan-2017

221 views

Category:

Technology


2 download

TRANSCRIPT

Page 1: Kotlin, smarter development for the jvm

Smarter development for the JVM

#GeekBreakFast

Kotlin

Page 2: Kotlin, smarter development for the jvm

@arnogiu

Work @ ekito

App & Gear Maker

Mobile & Cloud DevArnaud GIULIANI

Page 3: Kotlin, smarter development for the jvm

3

« production ready »15.02.2016

Page 4: Kotlin, smarter development for the jvm

Yet another JVM Language ?

Page 5: Kotlin, smarter development for the jvm

5

The new « Swift » for Android ?

https://goo.gl/W5g6Do - mid 2014

Page 6: Kotlin, smarter development for the jvm

Limits of java- Verbose

- Type inference

- No properties / Lazy / Delegate

- Checked exception

- NullPointerException

- Extensibility

- End of lines with ;

https://goo.gl/HIrmC9 @sdeleuze

Page 7: Kotlin, smarter development for the jvm

But Java is great …

- Fast

- Optimized bytecode

- Static typing

- Simple to learn

- Amazing ecosystem

Page 8: Kotlin, smarter development for the jvm

Today’s ITChallenge

Responsive

Resilient

Scalable

Productive

Page 9: Kotlin, smarter development for the jvm
Page 10: Kotlin, smarter development for the jvm

(not only) Functional programming

First class functions, immutability, no side effects,

conciseness …

Page 11: Kotlin, smarter development for the jvm

11

Ready for Reactive Programming

Page 12: Kotlin, smarter development for the jvm

How K can help you ?

- Conciseness

- Null Safety & Immutability protection

- Static Typing & Smart Casts

- Open programming styles (lambdas, high order functions …)

- Java interop

Page 13: Kotlin, smarter development for the jvm

What’sKotlin ?

- Fully open source (built by Jetbrains)

- Run on Java 6+

- Static typing & type inference

- Modern language features

- 1st grade tooling

Page 14: Kotlin, smarter development for the jvm

What’s insideKotlin ?

- 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

Page 15: Kotlin, smarter development for the jvm

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

Page 16: Kotlin, smarter development for the jvm

Use Cases

Source : poll on Kotlin Slack (early 2016)https://goo.gl/HIrmC9 @sdeleuze

Page 17: Kotlin, smarter development for the jvm

17

Want some nougat ?

Page 18: Kotlin, smarter development for the jvm

18

Slowing Deployment

https://goo.gl/2sOGBd

Page 19: Kotlin, smarter development for the jvm

19

Page 20: Kotlin, smarter development for the jvm

20

is Kotlin Android friendly ?

https://github.com/SidneyXu/AndroidDemoIn4Languages

Method counts by Language

Page 21: Kotlin, smarter development for the jvm

Where to use Kotlin ?*

*everywhere you use Java

Page 22: Kotlin, smarter development for the jvm

22

let’s go write some Kotlin !

Page 23: Kotlin, smarter development for the jvm

Ready to useEasy to run

Page 24: Kotlin, smarter development for the jvm

24

Getting started with gradle

buildscript { ext.kotlin_version = '<version to use>'

dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" }}

apply plugin: "kotlin"

dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"}

1.0.5-2

also available with maven

Page 25: Kotlin, smarter development for the jvm

25

IntelliJ

Page 26: Kotlin, smarter development for the jvm

26

Page 27: Kotlin, smarter development for the jvm

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

Page 28: Kotlin, smarter development for the jvm

Smarter development

with K

Page 29: Kotlin, smarter development for the jvm

29

Typing & Inference

val a: Int = 1val b = 1 // `Int` type is inferred

var x = 5 // `Int` type is inferred x += 1

Infered values

Mutable values

val : constant value - IMMUTABLE var : variable value - MUTABLE

USE VAL AS MUCH AS POSSIBLE !

Page 30: Kotlin, smarter development for the jvm

30

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 StringstringB = null //ok

Optional value

Page 31: Kotlin, smarter development for the jvm

31

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

Page 32: Kotlin, smarter development for the jvm

32

Example

Page 33: Kotlin, smarter development for the jvm

33

Class

class User ( var userName: String, var firstName: String, var lastName: String, var location: Point? = null )

POJO + - Getter- Setter- Constructors

Page 34: Kotlin, smarter development for the jvm

34

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

Page 35: Kotlin, smarter development for the jvm

35

POJO ?

Page 36: Kotlin, smarter development for the jvm

36

Properties

// readonly propertyval isEmpty: Boolean get() = this.size == 0

Properties can be declared in constructor or in class

You can also handle getter & setter

// customer getter & settervar stringRepresentation: String get() = this.toString() set(value) { setDataFromString(value) // parses the string and assigns values to other properties }

class ApiKey(var weatherKey: String, var geocodeKey: String){ var debug : Boolean = false}

Page 37: Kotlin, smarter development for the jvm

37

Object Component

// singleton object Resource { val name = "Name"}

println(" my resource is : ${Resource.name}")

class StringCalculator{ // class helper companion object{ val operators = arrayOf("+","-","x","/") } }

println(" my operators are : ${StringCalculator.operators}")

Singleton Class

Companion Object

Page 38: Kotlin, smarter development for the jvm

38

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 usage

Page 39: Kotlin, smarter development for the jvm

39

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 <range> ->is <type> ->

expression ->

when (s) { is String -> print("s is a string") else -> print("s is not a string") }

Page 40: Kotlin, smarter development for the jvm

40

Example

Page 41: Kotlin, smarter development for the jvm

41

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

Page 42: Kotlin, smarter development for the jvm

42

Lambdas

val fab = findViewById(R.id.fab) as FloatingActionButtonfab.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()

Page 43: Kotlin, smarter development for the jvm

43

Destructuring Data

fun extractDelimiter(input: String): Pair<String, String> = …

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 with data classes

Page 44: Kotlin, smarter development for the jvm

44

Collections

// immutable listval 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<String,String>()// direct map access map2["a"] = "my value"println(map2["a"])

// range for (i in 1..100) { //... }

Page 45: Kotlin, smarter development for the jvm

45

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

Page 46: Kotlin, smarter development for the jvm

Sweet stuffs for

Page 47: Kotlin, smarter development for the jvm

47

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

Page 48: Kotlin, smarter development for the jvm

Kotlin

Java

Page 49: Kotlin, smarter development for the jvm

Anko - Android DSL

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

Page 50: Kotlin, smarter development for the jvm
Page 51: Kotlin, smarter development for the jvm

One of our longest journey …

Page 52: Kotlin, smarter development for the jvm

Reactive Programming

Page 53: Kotlin, smarter development for the jvm

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

Page 54: Kotlin, smarter development for the jvm

54

Example - Rx/RetrofitKotlin

Java

Page 55: Kotlin, smarter development for the jvm

55

Example - Rx/Realm

Page 56: Kotlin, smarter development for the jvm

56

Just another hype JVM stuff ?

Page 57: Kotlin, smarter development for the jvm

57

Ready to go ?

Page 58: Kotlin, smarter development for the jvm

58

Production ready ?

Page 59: Kotlin, smarter development for the jvm

59

Always hard to start …

Page 60: Kotlin, smarter development for the jvm

60

Our feedback with K

- Easy to start small & grow (no big bang)

- Tool support is very good

- Great feedback about the language itself

- Stable in production !

- Magical conversion … but take care

- Hard to come back to java …

Page 61: Kotlin, smarter development for the jvm

61

IF YOU DON'T LOOK AT JAVA AND THINK, "THIS

COULD BE BETTER", DON'T SWITCH.

@RunChristinaRun

Page 62: Kotlin, smarter development for the jvm

62

Learning Kotlin

Page 63: Kotlin, smarter development for the jvm

63

Try Kotlin online http://try.kotlinlang.org/#/Examples/

Kotlin Referencehttps://kotlinlang.org/docs/reference/

Kotlin Cheat Sheet (by ekito)http://www.slideshare.net/arnaudgiuliani/kotlin-

cheat-sheet-by-ekito

Kotlin Communityhttps://kotlinlang.org/community.html

Page 64: Kotlin, smarter development for the jvm

64

Kotlin 1.1

Page 65: Kotlin, smarter development for the jvm

Thank you :)