Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Welcome Kotlin!

Welcome Kotlin!

A Kotlin introductory talk for the first mettup of the Kotlin User Group Milano (www.meetup.com/it-IT/KUG-Milan/)

Giacomo Bresciani

June 21, 2017
Tweet

More Decks by Giacomo Bresciani

Other Decks in Programming

Transcript

  1. Why Kotlin? • Big Java codebases at JetBrains • Java

    is old and has some major problems • Java slow development
  2. July 2011 JetBrains publicly unveils a new statically typed programming

    language for the JVM with first-class IDE support
  3. February 2012 • Apache 2.0 Open-Source license • github.com/JetBrains/Kotlin •

    Kompiler • IntelliJ IDEA plugin • Issue Tracker Kotlin goes Open Source
  4. April 2015 • Library for Android development • DSL to

    build Android layouts • Collection of very useful utilities to make Android development easier • Open Source Anko for Android is revealed
  5. February 2016 • Stable release • Production ready • Long-term

    backward compatibility Version 1.0 released
  6. March 2017 • Stable JavaScript support • Experimental support for

    coroutines • Type aliases, bound callable references, destructuring in lambdas Version 1.1 released
  7. • Kotlin bundled in Android Studio 3.0 • Google commitment

    to the language • Improved support on Android Android first-class support for Kotlin ! May 2017
  8. Concise • Variable declaration • String templates /* Read only

    */ val a: Int = 1 // Explicit type
 val b = 2 // Type inferred /* Mutable */ var mutable = 2
 mutable = 4 // Reassignment val world = "World!"
 
 val helloWorld1 = "Hello $world" // -> Hello World!
 val helloWorld2 = "Hello ${world.replace("!", "!!!")}" // -> Hello World!!!
  9. Concise data class Document(
 val name: String,
 val author: String,


    val creationDate: Date = Date()) val doc = Document(name = "Welcome Kotlin!", author = "Giacomo Bresciani") documents.filter { it.author == "Giacomo Bresciani" } 
 .sortedBy { it.name } 
 .forEach { print(it.name) } • Data classes • Named parameter & default values • Collections utils
  10. Safe val string: String = null Compilation error! val stringNullable:

    String? = null stringNullable.length Compilation error! stringNullable?.length // -> Null val stringLengthNullable: String? = stringNullable?.length?.toString() // -> Null • Null Safety val stringLength: String = stringNullable?.length?.toString() ?: "No string” stringNullable!!.length // Safe calls // Elvis operator // !! Operator NullPointerException
  11. Safe • “Immutability” fun printDocument(unknownDocument: Any) {
 if (unknownDocument is

    Document) 
 print(unknownDocument.name)
 } • Smart Cast val doc = Document(name = "Welcome Kotlin!", author = "Giacomo Bresciani") doc = Document(name = “New Document", author = “Peter Parker”) Compilation error!
  12. Interoperable • Java from Kotlin • Kotlin from Java import

    java.util.Date val now = Date() now.time // equivalent to now.getTime() Document doc = new Document("Welcome Kotlin!", "Giacomo Bresciani", new Date()); String author = doc.getAuthor();
  13. Tools friendly • Java to Kotlin converter • Kotlin bytecode

    decompiler • A lot of IntelliJ “Intention Actions” (alt + Enter) • Syntax highlight
  14. First class functions { text: String, separator: Char -> text.split(separator)

    } • Lambdas val lambda: (String, Char) -> List<String> = 
 { text: String, separator: Char -> text.split(separator) } • High-order functions listOf(1, 2, 3).map({ int: Int -> int * 3 }) listOf(1, 2, 3).map { int: Int -> int * 3 } listOf(1, 2, 3).map { it * 3 } Kotlin Features
  15. Extension functions fun String.isShorterThan(s: String): Boolean = this.length < s.length

    • Definition • Usage "Short".isShorterThan("Longer String") // True
 "Looooooooooooong String".isShorterThan("Shorter String") // False • Infix notation infix fun String.isShorterThan(s: String): Boolean = this.length < s.length "Short" isShorterThan "Longer String" // True
 "Looooooooooooong String" isShorterThan "Shorter String" // False Kotlin Features
  16. Everything is an expression val ageTitle = if(age < 18)

    "underage" else “adult" • If • When (Java’s switch with superpowers) val ageTitle = when {
 age < 18 -> "underage"
 age in 18..64 -> "adult"
 else -> "senior"
 } • Try-Catch val int: Int? = try { "23d".toInt() } catch (nfe: NumberFormatException) { null } Kotlin Features
  17. Sealed classes (AKA algebraic data types or sum types) sealed

    class ViewState {
 object Loading: ViewState()
 data class Error(val message: String): ViewState()
 data class Ready(val content: String): ViewState()
 } • Definition • When fun render(currentState: ViewState) = when (currentState) {
 ViewState.Loading -> print("Loading...")
 is ViewState.Error -> print(currentState.message)
 is ViewState.Ready -> print(currentState.content)
 } Kotlin Features
  18. Kotlin Standard Library • A lot of utils ext. functions

    to query collections public inline fun <T> Iterable<T>.forEach(action: (T) -> Unit): Unit public inline fun <T> Iterable<T>.filter(predicate: (T) -> Boolean): List<T> public fun <T> List<T>.asReversed(): List<T> public inline fun <T> Iterable<T>.find(predicate: (T) -> Boolean): T? Kotlin Features public inline fun <T> T.apply(block: T.() -> Unit): T public inline fun <T, R> T.let(block: (T) -> R): R public inline fun <T : Closeable?, R> T.use(block: (T) -> R): R • Functions implementing idiomatic patterns
  19. Options • You can still of course use JUnit •

    Mockito, Hamcrest… • You can write really expressive tests • Core library: kotlin.test Testing
  20. Libraries • Spek - Specification Framework for the JVM class

    SumTest : Spek({
 describe("sum() function") {
 it("should return the sum of first number plus the second number") {
 val sum = sum(2, 4)
 assertEquals(6, sum)
 }
 }
 }) • KotlinTest - flexible and comprehensive testing tool “my string".length shouldBe 9 “hello" shouldNot haveSubstring(“olleh")
  21. Getting started • Bundled into recent version of IntelliJ IDEA

    and Android Studio 3.0 • Plugin available for Android Studio < 3.0 • Plugin available also for Eclipse • Build with Gradle, Maven, Ant
  22. First steps • Write some unit tests • Write some

    Utils functions • Introduce it gradually into you codebase • Experiment with pet project
  23. Tips! • Use the IntelliJ built-in Java converter • Force

    you to write idiomatic Kotlin code • Explore Kotlin stdlib • Keep calm and write readable code!
  24. Contribute! • KEEP - Kotlin Evolution and Enhancement Process github.com/Kotlin/KEEP

    • Proposal for the language (repo issues) • Issue Tracker - youtrack.jetbrains.com/issues/KT • Slack - slack.kotlinlang.org
  25. Books Resources • Kotlin in Action • Kotlin for Android

    Developers by Dmitry Jemerov and Svetlana Isakova by Antonio Leiva
  26. Other resources Resources • Kotlin Weekly • Kotlin Official Blog

    • Awesome Kotlin - kotlin.link • Talking Kotlin (podcast) - talkingkotlin.com