An Introduction to Kotlin

An Introduction to Kotlin

Kotlin sure has been receiving a lot of buzz lately, is there something to it? Developed by JetBrains, Kotlin has been catching on lately because of its null safety guarantees, functional nature, type inference, full interoperability with Java, cross-platform support, and ease of use with Android and Spring. Is this something you and your team should considering spending time to learn?

One of the most interesting aspects of Kotlin is its design philosophy. Bugs that exist in Java such as NullPointerExceptions are not possible in Kotlin. This mentality of preventing common bugs at the language level exists all through the Kotlin syntax and standard library. Kotlin is also far less verbose than Java, reducing the amount of code you need to read in order to understand it. It also runs on JVMs down to Java 6, without sacrificing features. So if you are in a constrained environment such as Android or an enterprise shop struggling to upgrade, Kotlin might be worth considering.

In this talk, you will learn where Kotlin came from, what its major features are, and why people are using it more and more. At the end of the talk, you will be in a position to make an educated decision about whether Kotlin is right for you!

2777430c1f9869e411ab5d8b17d8ba2a?s=128

Todd Ginsberg

June 19, 2019
Tweet

Transcript

  1. An Introduction To Kotlin Kansas City Java User Group 2019-06-19

    Todd Ginsberg ` @ToddGinsberg Principal Software Developer
  2. @ToddGinsberg What’s in a Name? By Editors of Open Street

    Map - Open Street Map, CC BY-SA Kotlin Island
  3. @ToddGinsberg But First… I Java

  4. @ToddGinsberg Who Is This Person? Todd Ginsberg Principal Software Developer

    @Netspend (a payments company in Austin, TX) Java developer since 1995 Kotlin developer since 2016 Chicago Java User Group Board Member and CFO
  5. @ToddGinsberg Agenda 1.What is Kotlin? 2.Am I Alone? 3.Syntax and

    Code 4.Community 5.Summary / Wrap-up 6.Q & A
  6. @ToddGinsberg What Is Kotlin?

  7. @ToddGinsberg What Is Kotlin? Statically typed language, developed by JetBrains

    Released under Apache 2.0 license Designed as a general purpose language • Targets JVM bytecode 6 through 12 • Targets ECMAScript 5.1 • Targets native thanks to LLVM
  8. @ToddGinsberg Major Features 100% interoperable with Java Very easy to

    learn Fantastic IDE support Large, positive community Pragmatic – No shame in copying language features that make developers more productive
  9. @ToddGinsberg Major Features Designed to avoid entire classes of defects

    Null-safe 185,000+ issues on GitHub! 13,959 duplicates on Stack Overflow! Type Inference More than diamond operator or local var (thanks Java 10!)
  10. @ToddGinsberg Am I Alone?

  11. @ToddGinsberg Supported on Android Beep! You can use Kotlin now!

    2017
  12. @ToddGinsberg Supported on Android Beep! Prefer Kotlin over Java! 2018

  13. @ToddGinsberg Supported on Android Beep! Android is now Kotlin-first! 2019

  14. @ToddGinsberg Spring Framework Support Kotlin is fully supported in Spring

    Framework 5 Kotlin is an option on start.spring.io Spring @NotNull annotations == Better Kotlin nullability support Comprehensive Kotlin documentation and examples
  15. @ToddGinsberg Supported in Gradle

  16. @ToddGinsberg Kotlin Adoption MAR 2017 Assess NOV 2017 Trial MAY

    2018 Adopt ThoughtWorks Technology Radar
  17. @ToddGinsberg Syntax

  18. @ToddGinsberg Variables and Values var place: String = "Chicago" place

    = "Illinois" // OK! val name: String = "Todd" name = "Emma" // Compile Error!
  19. @ToddGinsberg Type Inference val d: Int = 2 val description:

    String = "Todd has $d doughnuts"
  20. @ToddGinsberg val d = 2 val description = "Todd has

    $d doughnuts" Type Inference
  21. @ToddGinsberg Equality val name1 = "EXAMPLE" val name2 = "example"

    // Structural Equality name1 == name2.toUpperCase() // True! // Referential Equality name1 === name2 // False! // Unfortunately… name1 ==== name2 // Compiler Error L
  22. @ToddGinsberg Raw Strings val json = "{\n\"name\": \"Todd\"\n}” val json

    = """ { "name": "Todd" } """ val json = """{ "name": "Todd" }"""
  23. @ToddGinsberg Null Safety // Guaranteed to never be null val

    name: String = "Todd" // May be null val salary: Int? = null
  24. @ToddGinsberg var city: String? = "Chicago" // Not allowed, might

    be null! city.toUpperCase() // Safe traversal city?.toUpperCase() Null-safe Traversal
  25. @ToddGinsberg val lowest : Int? = listOf(1, 2, 3).min() val

    lowest : Int = listOf(1, 2, 3).min() ?: 0 Elvis
  26. @ToddGinsberg Combine Safe-Traversal and Elvis println( city?.toUpperCase() ?: ”UNKNOWN” )

  27. @ToddGinsberg val lowest: Int? = listOf(1, 2, 3).min() val lowest:

    Int = listOf(1, 2, 3).min()!! val lowest: Int = emptyList<Int>().min()!! // KotlinNullPointerException! L Manual Override
  28. @ToddGinsberg Null Safety Remember the names! ?. == Safe Traversal

    ?: == Elvis !! == Hold My Beer
  29. @ToddGinsberg Expressions – if val status = if (code ==

    42) { "Success" } else { "Fail" }
  30. @ToddGinsberg Expressions – try/catch val number = try { code.toInt()

    } catch (e: NumberFormatException) { 0 }
  31. @ToddGinsberg Expressions – When val result = when (x) {

    0 -> "x is 0” in 1..10 -> "x is between 1 and 10" in someSet -> "x is in someSet" is SomeType -> "x is an instance of SomeType" parseString(s) -> "the same as parseString" else -> "x doesn't match anything" }
  32. @ToddGinsberg when (x) { is Int -> print(x % 2

    == 0) is String -> print(x.length + 1) is IntArray -> print(x.sum()) } if(x != null) { println(x.toString()) } Smart Casting
  33. @ToddGinsberg Classes class Entity : SomeInterface { // ... }

  34. @ToddGinsberg Classes - Inheritance open class Entity : SomeInterface {

    // ... } class Customer : Entity() { // ... }
  35. @ToddGinsberg Properties class Customer(var name: String) { var state: String?

    = null } val c = Customer("Todd") c.state = "IL" println("${c.name} from ${c.state}") // "Todd from IL"
  36. @ToddGinsberg Properties – Set class Customer(var name: String) { var

    state: String? = null set(value) { field = value?.toUpperCase() } }
  37. @ToddGinsberg Properties – Set class Customer(var name: String) { var

    state: String? = null private set(value) { field = value?.toUpperCase() } }
  38. @ToddGinsberg Properties – GET class Customer(var name: String) { var

    state: String? = null get() { return field?.toUpperCase() } }
  39. @ToddGinsberg Property Delegation class Country { val gdp: Int =

    slowCalculation() } class Country { val gdp: Int by lazy { slowCalculation() } }
  40. @ToddGinsberg Class Delegation // Java class MyJavaImpl implements HugeInterface {

    private final HugeInterface backing; public MyJavaImpl(HugeInterface hi) { backing = hi; } // IMPLEMENT EVERYTHING }
  41. @ToddGinsberg Class Delegation // Java class MyJavaImpl extends SomeImplementation {

    // Implement Some }
  42. @ToddGinsberg Class Delegation // Kotlin class MyImpl(h: HugeInterface) : HugeInterface

    by h { // Implement Some }
  43. @ToddGinsberg Sealed Classes sealed class Message class StartServer(val name: String)

    : Message() class StopServer(val name: String) : Message() object CountServers : Message()
  44. @ToddGinsberg Sealed Classes val response = when(msg) { is StartServer

    -> startServer(msg.name) is StopServer -> stopServer(msg.name) is CountServers -> countServers() }
  45. @ToddGinsberg Let’s Write a POJO! public class Person { public

    String firstName; public String lastName; }
  46. @ToddGinsberg Let’s Write a POJO! public class Person { private

    String firstName; private String lastName; public String getFirstName() { return firstName; } public void setFirstName(final String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(final String lastName) { this.lastName = lastName; } }
  47. @ToddGinsberg Let’s Write a POJO! public class Person { private

    String firstName; private String lastName; public Person() { } public Person(final String firstName, final String lastName) { this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return firstName; } public void setFirstName(final String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(final String lastName) { this.lastName = lastName; } }
  48. @ToddGinsberg Let’s Write a POJO! import java.util.Objects; public class Person

    { private String firstName; private String lastName; public Person() { } public Person(final String firstName, final String lastName) { this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return firstName; } public void setFirstName(final String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(final String lastName) { this.lastName = lastName; } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final Person person = (Person) o; return Objects.equals(firstName, person.firstName) && Objects.equals(lastName, person.lastName); } @Override public int hashCode() { return Objects.hash(firstName, lastName); } }
  49. @ToddGinsberg Let’s Write a POJO! import java.util.Objects; public class Person

    { private String firstName; private String lastName; public Person() { } public Person(final String firstName, final String lastName) { this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return firstName; } public void setFirstName(final String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(final String lastName) { this.lastName = lastName; } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final Person person = (Person) o; return Objects.equals(firstName, person.firstName) && Objects.equals(lastName, person.lastName); } @Override public int hashCode() { return Objects.hash(firstName, lastName); } @Override public String toString() { return "Person{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + '}'; } }
  50. @ToddGinsberg Data Classes To The Rescue! data class Person(val firstName:

    String, val lastName: String) • Getters (and Setters for vars) as Properties • toString() • hashCode() and equals() • And…
  51. @ToddGinsberg Copying Data Classes val me = Person("Todd", "Ginsberg") val

    emma = me.copy(firstName = "Emma") // Person(”Emma", "Ginsberg")
  52. @ToddGinsberg Destructuring Data Classes val me = Person("Todd", "Ginsberg") val

    (first, last) = me // first == “Todd” last == “Ginsberg”
  53. @ToddGinsberg FUNctions! fun generateRandomNumber(): Int { return 4 } fun

    generateRandomNumber(): Int = 4 fun generateRandomNumber() = 4
  54. @ToddGinsberg FUNctions – Default Values fun random(offset: Int = 0):

    Int = offset + 4 random() // 4 random(1) // 5
  55. @ToddGinsberg FUNctions – Named Parameters fun combine(first: Int, second: Int):

    Int = first + second combine(1, 2) // 3 combine(first = 1, second = 2) // 3 combine(second = 2, first = 1) // 3
  56. @ToddGinsberg FUNctions – Named & Default fun combine(first: Int, second:

    Int, third: Int = 0): Int = first + second + third combine(1, 2) // 3 combine(second = 2, first = 1, third = 3) // 6
  57. @ToddGinsberg FUNction Names @Test fun `Replicants have a four year

    lifespan!`() { // ... } @Test fun replicantsHaveAFourYearLifespan() { // ... }
  58. @ToddGinsberg Operator Overloading Limited overloading – cannot define your own

    operators. Expression Translated to a + b a.plus(b) a - b a.minus(b) a * b a.times(b) a / b a.div(b) a % b a.rem(b) a..b a.rangeTo(b)
  59. @ToddGinsberg Operator Overloading Limited overloading – cannot define your own

    operators. Expression Translated to a in b b.contains(a) a !in b !b.contains(a)
  60. @ToddGinsberg Operator Overloading Limited overloading – cannot define your own

    operators. Expression Translated to a[i] a.get(i) a[i] = b a.set(i, b)
  61. @ToddGinsberg Operator Overloading Limited overloading – cannot define your own

    operators. Expression Translated to a += b a.plusAssign(b) a -= b a.minusAssign(b) a *= b a.timesAssign(b) a /= b a.divAssign(b) a %= b a.remAssign(b)
  62. @ToddGinsberg Operator Overloading Limited overloading – cannot define your own

    operators. Expression Translated to a > b a.compareTo(b) > 0 a < b a.compareTo(b) < 0 a >= b a.compareTo(b) >= 0 a <= b a.compareTo(b) <= 0
  63. @ToddGinsberg fun measureTimeMillis(block: () -> Unit): Long { val start

    = System.currentTimeMillis() block() return System.currentTimeMillis() - start } val time = measureTimeMillis { someSlowQuery() } High Order FUNctions
  64. @ToddGinsberg Extension FUNctions // Java public static boolean isEven(int i)

    { return i % 2 == 0; } // Kotlin fun Int.isEven(): Boolean = this % 2 == 0 2.isEven() // True!
  65. @ToddGinsberg The use Extension // Java try (DatabaseConnection conn =

    getConnection()) { // ... } // Kotlin getConnection().use { conn -> // ... }
  66. @ToddGinsberg The apply Extension // Expression and Statements val p

    = Person() p.name = "Todd" p.age = 21 // Single Expression val p = Person().apply { name = "Todd" age = 21 }
  67. @ToddGinsberg One More Thing On FUNctions… Functions are final by

    default. Arguments are always final. Functions can be defined in a file, outside of a class. Functions can be defined within another function. Kotlin supports tail recursive functions.
  68. @ToddGinsberg What About Checked Exceptions? NO

  69. @ToddGinsberg listOf(1, 2, 3, 4) .filter { x -> x

    % 2 == 0 } .map { y -> y * 2 } // List[4, 8] Lambdas
  70. @ToddGinsberg Lambdas listOf(1, 2, 3, 4) .filter { it %

    2 == 0 } .map { it * 2 } // List[4, 8]
  71. @ToddGinsberg Lambdas Are Closures val ints = listOf(1, 2, 3,

    4) var sum = 0 ints.forEach { sum += it } println(sum) // 10
  72. @ToddGinsberg Type Aliases fun doSomethingWithMap( ops: Map<SomeType, List<String>> ) {

    ops.entries // ... }
  73. @ToddGinsberg Type Aliases typealias Operations = Map<SomeType, List<String>> fun doSomethingWithMap(ops:

    Operations) { ops.entries // … }
  74. @ToddGinsberg Import Aliases import java.util.Date import java.sql.Date

  75. @ToddGinsberg Import Aliases import java.util.Date as UtilDate import java.sql.Date as

    SqlDate
  76. @ToddGinsberg Import Aliases import java.util.Date as SqlDate import java.sql.Date as

    UtilDate
  77. @ToddGinsberg Reified Generics // Ugly val log = Logger.getLogger(Metrics::class.java) //

    What I want val log = loggerOf<Metrics>()
  78. @ToddGinsberg // Thanks type erasure L fun <T> loggerOf(): Logger

    = Logger.getLogger(T::class.java) Reified Generics
  79. @ToddGinsberg inline fun <reified T> loggerOf(): Logger = Logger.getLogger(T::class.java) //

    Works! val log = loggerOf<Metrics>() Reified Generics
  80. @ToddGinsberg Community

  81. @ToddGinsberg Community Resources https://kotlinlang.slack.com • 22,000+ members • Get answers

    and chat with people who work with the language • Welcoming and helpful • Language authors hang out here Stack Overflow • Actually get meaningful answers • Not uncommon to get many useful answers • Language authors here as well
  82. @ToddGinsberg Community KΛTEGORY funKTionale Λrrow

  83. @ToddGinsberg Try Kotlin! https://play.kotlinlang.org

  84. @ToddGinsberg Learn Kotlin! https://bit.ly/GoogleKotlinClass

  85. @ToddGinsberg Learn Kotlin! https://www.coursera.org/learn/kotlin-for-java-developers

  86. @ToddGinsberg Fun == Fun Kotlin % of developers who are

    developing with the language or technology but have not expressed interest in continuing to do so (Stack Overflow Developer Survey 2019)
  87. @ToddGinsberg Summary

  88. @ToddGinsberg Make “Bad” Choices Explicit or Impossible Fixed in Kotlin:

    - Singleton support built in - Override keyword mandatory - Properties over fields with getter/setter - Mutability is minimized (val + collections) - Inheritance prohibited by default - Builders are easy with default values - No checked exceptions - Structural equality is the same everywhere - Delegation support makes composition easier
  89. @ToddGinsberg Why Kotlin is Right For Me I write far

    less code. The code I write is more expressive and clear. I avoid whole classes of defects. Allows me to write in a more functional style. Writing Kotlin, for me, is more fun. Plays well with the tools I already use (Spring, IDEA, Gradle)
  90. @ToddGinsberg Is Kotlin is Right For You?

  91. Than You! @ToddGinsberg https://todd.ginsberg.com todd@ginsberg.com Anonymous Feedback