Android, Spring, Gradle et de nombreux autres projets apportent leur soutien au langage Kotlin. Fin 2017, Kotlin tient-il ses promesses ?
Retour d’expérience sur le langage, ses avantages et inconvénients sur un projet Mobile, un projet Back et bien plus.
3. Historique
Historique
Motivations du projet
▼ Besoin d’un nouveau langage
▽ Plus riche que Java mais JVM-compatible
▽ Plus riche et simple que d’autres langages JVM
▼ Statiquement typé, orienté objet et fonctionnel
▼ Pragmatisme
▽ Utilité des fonctionnalités
▽ Réutilisation du code et des outils
https://www.infoworld.com/article/2622405/java/jetbrains-readies-jvm-based-language.html
https://blog.jetbrains.com/kotlin/2016/02/kotlin-1-0-released-pragmatic-language-for-jvm-and-android/
3
7. Apports clés du langage
Apports clés du langage
Un peu de Code !
7
8. Apports clés du langage
Un programme simple en Kotlin
Hello Kotlin
val bob = "Bob"
fun greet(name: String) = "Hello $name"
fun main(args: Array<String>) {
println(greet(bob))
}
8
9. Apports clés du langage
Références non nullables par défaut
Quelles NullPointerException ?
class Address(val city: String)
class User(val name: String, val address: Address?)
val user1 = User("Bob", Address("Paris"))
val user2 = User("Bob", null)
val city = user2.address?.city ?: "Unknown"
https://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare
9
10. Apports clés du langage
Inférence de type par branche
Smart Cast
interface Price
class StandardPrice(val value: Int) : Price
class PromotionalPrice(val value: Int, val discount: Int) :
Price
fun computePrice(price: Price): Int = when (price) {
is StandardPrice -> price.value
is PromotionalPrice -> price.value - price.discount
else -> 0
} 10
11. Apports clés du langage
Fonctions en tant que variables
Lambda
val greet: (String) -> String = { name -> "Hello $name" }
fun addEventListener(listener: (Event) -> Unit) {
// ...
}
addEventListener {
it.key
// ...
} 11
12. Apports clés du langage
Augmenter du code existant facilement
Extension
fun Int.square(): Int = this * this
val result = 42.square()
fun String.greet(): String = "Hello $this"
val greet = "Bob".greet()
12
13. Apports clés du langage
Data class, Destructuration, Collections
Et tellement plus
data class MyTime(val hour: Int, val minute: Int)
val copy = MyTime(11, 11).copy(hour = 15)
val times = listOf(MyTime(11, 11), MyTime(12, 34))
times.map { (hour, minute) -> "$hour:$minute" }
13
14. Où est mon Kotlin ?
Kotlin est partout
Applications Back
▼ **/*.jar
▼ Build Gradle en Kotlin
▼ Spring / Spring Boot
▼ RxJava / RxKotlin
▼ Reactor (Natif)
▼ Jackson
https://spring.io/blog/2016/02/15/developing-spring-boot-applications-with-kotlin
https://spring.io/blog/2017/03/28/reactor-kotlin-extensions-1-0-0-m1-released
https://spring.io/blog/2017/08/01/spring-framework-5-kotlin-apis-the-functional-way
https://github.com/ReactiveX/RxKotlin
14
15. Où est mon Kotlin ?
Kotlin est partout
Application classique Spring Boot
fun main(args: Array<String>) {
runApplication<Application>(*args)
}
@RestController
@SpringBootApplication
class Application {
@GetMapping
fun hello() = "Hello World"
} 15
16. Où est mon Kotlin ?
Kotlin est partout
Langage augmenté par les bibliothèques
data class User(val name: String, val age: Int)
val mapper = ObjectMapper().registerModule(KotlinModule())
mapper.writeValueAsString(User("Bob", 30))
listOf(User("Bob", 30), User("Alice", 30))
.toFlux()
.sample(Duration.ofMillis(100))
.subscribe(::println)
16
17. Où est mon Kotlin ?
Kotlin est partout
Sur Android
vs
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_game)
nameTextView.text = "Hey"
}
17
18. Où est mon Kotlin ?
Kotlin est partout
Sur Android
private val timeFormat: SimpleDateFormat by lazy {
SimpleDateFormat(getString(R.string.hour_pattern), Locale.getDefault())
}
override fun onBindViewHolder(holder: MyViewHolder?, position: Int) {
val view = holder?.itemView
when (view) {
is TextView -> view.text = "hey"
is ImageView -> view.setImageDrawable(ContextCompat.getDrawable(context,
R.mipmap.ic_launcher))
}
} 18
19. Qualité du code
Tests
Outillage de test en Kotlin
▼ JUnit
▼ Spek
▽ given, on, it / describe, on, it
▽ Pas d’assertions
▼ KotlinTest
▽ Port de ScalaTest
▽ Assertions
http://junit.org/junit5/
https://github.com/kotlintest/kotlintest
http://spekframework.org/docs/
19
20. Qualité du code
Tests
Exemple avec KotlinTest
mapOf(-1 to 1, 1 to 1, 2 to 2, 3 to 6, 4 to 24).forEach {
"factorial(${it.key}) should be ${it.value}" {
factorial(it.key).shouldBe(it.value)
}
}
20
21. Qualité du code
Analyse syntaxique et bugs
https://github.com/arturbosch/sonar-kotlin
21
KO
KO
OK
OK
OKOK
22. Qualité du code
Analyse syntaxique et bugs
https://github.com/arturbosch/detekt
https://ktlint.github.io/
22
24. Merci
Essayer Kotlin c’est l’adopter !
▼ 100% interopérable avec Java
▼ Null-safety
▼ Smart casts
▼ Lambda & fonction inline
▼ Data classes
24
Q/A
Benjamin Lacroix
@benjlacroix
Sergio Dos Santos
@sergiodsr
25. Un slide
Pourquoi Kotlin
un autre titre
Permet à minima la même chose que Java, en plus concis et plus élégant ; sur Android
apporte les nouveautés Java 8, 9 et +
Plus sur et concis que JavaScript tout en gardant la même expressivité
Kotlin s’inspire de Groovy, apparaît 8 ans après et est statiquement typé rendant le
code plus fiable à la compilation
Scala a été créé en université, Kotlin chez un éditeur de logiciel ; le second a été pensé
pour compiler rapidement et bénéficier de bons outils de support. Kotlin est pensé
pour fonctionner avec Java, Scala peut fonctionner avec Java
Swift est comme Kotlin, Kotlin est comme Swift, 2 langages, 2 plateformes
25
26. Où est mon Kotlin ?
Kotlin est partout
Dans le navigateur ou dans Node
Depuis septembre 2016
Compiler Kotlin en Javascript via
● Gradle
● Intellij Idea
● Maven
● La ligne de commande
Interaction avec le DOM
Kotlinx.html pour générer des éléments HTML
fun main(args: Array<String>) {
println("Hello JavaScript!")
}
https://kotlinlang.org/docs/tutorials/javascript/kotlin-to-javascript/kotlin-to-javascript.html
26
27. Apports clés du langage
Hiérarchie de classe fermée
Sealed Class
sealed class Price
class StandardPrice(val value: Int) : Price()
class PromotionalPrice(val value: Int, val discount: Int) :
Price()
fun computePrice(price: Price): Int = when (price) {
is StandardPrice -> price.value
is PromotionalPrice -> price.value - price.discount
// else -> 0
} 27
28. Agenda
CFP : https://cfp.xebicon.fr/cfp/proposal/edit/ELM-6166
Talk : FR
Format : Fast Track ~15min + ~5min de QA
Why : Kotlin est-il production ready?
Plan :
● Historique rapide de Kotlin
● Fast forward Kotlin jusqu’à la Keynote IO B
● Apport(s) clé(s) du langage !
● Feedback Kotlin everywhere (Back, Mobile, Front, Native)
a. Back: SpringBoot / Vertx / Ktor
b. Mobile: Coroutines / Lambdas / … B
c. Native / Front: Native => alpha, Front => mappings ts (pas trop de détail là dessus) B
● Code quality
a. Tests: JUnit5 / Spek / Kotlin-test
b. Linters ? Sonar ? B
● Pourquoi Kotlin et pas Java / Scala / Groovy / Javascript (à discuter, cf. prez sdeleuze)
● Next step B
a. Faites du Kotlin, l’adopter c’est l’aimer
28
29. Apports clés du langage
Créer des builders simplement
Extension en paramètre
fun build(name: String, init: Build.() -> Unit): Build {
val build = Build(name)
build.init()
return build
}
fun myBuild() = build("myProject") {
dependency("libA")
dependency("libB")
} 29