An Introduction to Kotlin

An Introduction to Kotlin

Kotlin has been catching on lately as an alternative to Java because of its null safety guarantees, type inference, cross-platform support, and ease of use with Android and Spring. Not to mention the fact that it is fully interoperable with Java. Is this something you and your team should considering spending time to learn?

Come to this session for an overview of Kotlin intended for Java developers (don't worry if you don't know Java, Kotlin is very easy to learn!). We will go over the major language features, syntax, and the Kotlin ecosystem so you'll know enough to make your own decisions by the end.

You will come away from this session with enough knowledge to decide if this is something you and your team should consider adopting.

2777430c1f9869e411ab5d8b17d8ba2a?s=128

Todd Ginsberg

October 11, 2019
Tweet

Transcript

  1. 2.
  2. 6.

    @ToddGinsberg Kotlin in 30 Minutes?! No, that’s crazy! (But come

    have lunch with me after!) (Or come to the open space!)
  3. 10.
  4. 11.

    @ToddGinsberg Agenda - What Is Kotlin? - Am I Alone?

    - Syntax & Features - Summary - Questions?
  5. 14.

    @ToddGinsberg Who is this Guy? Todd Ginsberg Just moved to

    Dallas from Chicago Principal Developer at Netspend - A payments company in Austin, TX! - We love Kotlin and Java!
  6. 18.

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

    Released under Apache 2.0 license Designed as a general purpose language
  7. 19.

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

    Released under Apache 2.0 license Designed as a general purpose language • Targets JVM 6 or 8 bytecode
  8. 20.

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

    Released under Apache 2.0 license Designed as a general purpose language • Targets JVM 6 or 8 bytecode • Targets ECMAScript 5.1
  9. 21.

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

    Released under Apache 2.0 license Designed as a general purpose language • Targets JVM 6 or 8 bytecode • Targets ECMAScript 5.1 • Targets other native platforms thanks to LLVM
  10. 24.

    @ToddGinsberg Major Features 100% Interoperable with Java Designed to avoid

    entire classes of defects Lots of small improvements that add up
  11. 25.

    @ToddGinsberg Major Features 100% Interoperable with Java Designed to avoid

    entire classes of defects Lots of small improvements that add up Far less code to accomplish the same task in Java - Less cognitive load on developers
  12. 35.

    @ToddGinsberg Spring Framework Support Kotlin is fully supported since Spring

    Framework 5 Kotlin is an option on start.spring.io
  13. 36.

    @ToddGinsberg Spring Framework Support Kotlin is fully supported since Spring

    Framework 5 Kotlin is an option on start.spring.io Spring @NotNull annotations == Better Kotlin nullability support
  14. 37.

    @ToddGinsberg Spring Framework Support Kotlin is fully supported since Spring

    Framework 5 Kotlin is an option on start.spring.io Spring @NotNull annotations == Better Kotlin nullability support Comprehensive Kotlin documentation and examples
  15. 42.
  16. 43.

    @ToddGinsberg Variables and Values var place: String = "Huntsville" place

    = "Alabama" // OK! val name: String = "Todd" name = "Emma" // Compile Error!
  17. 44.
  18. 45.
  19. 48.

    @ToddGinsberg Equality val name1 = "EXAMPLE" val name2 = "example"

    // Structural Equality name1 == name2.toUpperCase() // True!
  20. 49.

    @ToddGinsberg Equality val name1 = "EXAMPLE" val name2 = "example"

    // Structural Equality name1 == name2.toUpperCase() // True! // Referential Equality name1 === name2 // False!
  21. 54.

    @ToddGinsberg Null Safety // Guaranteed to never be null var

    name: String = "Todd" // May be null var salary: Int? = null
  22. 56.
  23. 57.

    @ToddGinsberg Null-Safe Traversal var city: String? = "Huntsville" // Not

    allowed, might be null! city.toUpperCase() // Safe traversal city?.toUpperCase()
  24. 59.

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

    val lowest : Int = listOf(1, 2, 3).min() ?: 0
  25. 62.

    @ToddGinsberg Hey Kotlin, Hold My Beer! val lowest: Int? =

    listOf(1, 2, 3).min() val lowest: Int = listOf(1, 2, 3).min()!!
  26. 63.

    @ToddGinsberg Hey Kotlin, Hold My Beer! val lowest: Int? =

    listOf(1, 2, 3).min() val lowest: Int = listOf(1, 2, 3).min()!! val lowest: Int = emptyList<Int>().min()!!
  27. 64.

    @ToddGinsberg Hey Kotlin, Hold My Beer! val lowest: Int? =

    listOf(1, 2, 3).min() val lowest: Int = listOf(1, 2, 3).min()!! val lowest: Int = emptyList<Int>().min()!! // NullPointerException!
  28. 65.
  29. 66.
  30. 67.

    @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" }
  31. 68.

    @ToddGinsberg Smart Casting when (x) { is Int -> print(x

    % 2 == 0) is String -> print(x.length + 1) is IntArray -> print(x.sum()) }
  32. 69.

    @ToddGinsberg Smart Casting when (x) { is Int -> print(x

    % 2 == 0) is String -> print(x.length + 1) is IntArray -> print(x.sum()) }
  33. 72.

    @ToddGinsberg Classes - Inheritance open class Entity : SomeInterface {

    // ... } class Customer : Entity() { // ... }
  34. 73.

    @ToddGinsberg Properties public class Customer { private String name; public

    String getName() { return name; } public void setName(final String name) { this.name = name; } }
  35. 77.

    @ToddGinsberg Properties class Customer { var name: String? = null

    } val c = Customer() c.name = "Todd" println("My name is ${c.name}")
  36. 79.

    @ToddGinsberg Properties class Customer { var name: String? = null

    set(value) { field = value?.toUpperCase() } }
  37. 80.

    @ToddGinsberg Properties class Customer { var name: String? = null

    private set(value) { field = value?.toUpperCase() } }
  38. 81.
  39. 82.

    @ToddGinsberg Let’s Write a POJO! public class Person { public

    String firstName; public String lastName; }
  40. 83.

    @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; } }
  41. 84.

    @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; } }
  42. 85.

    @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); } }
  43. 86.

    @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 + '\'' + '}'; } }
  44. 88.

    @ToddGinsberg Data Classes to the Rescue! data class Person(val firstName:

    String, val lastName: String) • Getters (and Setters for vars) as Properties
  45. 89.

    @ToddGinsberg Data Classes to the Rescue! data class Person(val firstName:

    String, val lastName: String) • Getters (and Setters for vars) as Properties • toString()
  46. 90.

    @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()
  47. 91.

    @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…
  48. 93.

    @ToddGinsberg Copying Data Classes val me = Person("Todd", "Ginsberg") val

    emma = me.copy(firstName = "Emma") // Person(”Emma", "Ginsberg")
  49. 96.

    @ToddGinsberg FUNctions! fun generateRandomNumber(): Int { return 4 } fun

    generateRandomNumber(): Int = 4 fun generateRandomNumber() = 4
  50. 99.

    @ToddGinsberg FUNctions - Default Values fun random(offset: Int = 0):

    Int = offset + 4 random() // 4 random(1) // 5
  51. 102.

    @ToddGinsberg FUNctions - Adding Parameters fun combine(first: Int, second: Int,

    third: Int = 0): Int = first + second + third combine(1, 2) combine(1, 2, 3)
  52. 105.

    @ToddGinsberg FUNctions - Named Parameters fun combine(first: Int, second: Int):

    Int = first + second combine(first = 1, second = 2) // 3
  53. 106.

    @ToddGinsberg FUNctions - Named Parameters fun combine(first: Int, second: Int):

    Int = first + second combine(second = 2, first = 1) // 3
  54. 115.

    @ToddGinsberg The apply Extension // Single Expression val p =

    Person().apply { name = "Todd" age = 21 }
  55. 116.

    @ToddGinsberg The apply Extension // Single Expression val p =

    Person().apply { name = "Todd" age = 21 address = Address().apply { line1 = "5 Tall Cedar Rd." … } }
  56. 118.

    @ToddGinsberg One More Thing on FUNctions • Functions are final

    by default. • Arguments are always final.
  57. 119.

    @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.
  58. 120.

    @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.
  59. 121.

    @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.
  60. 124.

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

    x % 2 == 0 } .map { y -> y * 2 } // List[4, 8]
  61. 125.

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

    x % 2 == 0 } .map { y -> y * 2 } // List[4, 8]
  62. 126.

    @ToddGinsberg Lambdas listOf(1, 2, 3, 4) .filter { it %

    2 == 0 } .map { it * 2 } // List[4, 8]
  63. 128.

    @ToddGinsberg Reified Generics // Thanks type erasure :( fun <T>

    loggerOf(): Logger = Logger.getLogger(T::class.java)
  64. 130.

    @ToddGinsberg Reified Generics inline fun <reified T> loggerOf(): Logger =

    Logger.getLogger(T::class.java) // Works! val log = loggerOf<Metrics>()
  65. 132.

    @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
  66. 137.

    @ToddGinsberg Why Do I Use Kotlin? • I write far

    less code. • The code I write is more expressive and clear.
  67. 138.

    @ToddGinsberg Why Do I Use Kotlin? • I write far

    less code. • The code I write is more expressive and clear. • I avoid whole classes of defects.
  68. 139.

    @ToddGinsberg Why Do I Use Kotlin? • 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.
  69. 140.

    @ToddGinsberg Why Do I Use Kotlin? • 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. • Plays well with the tools I use (Spring, IDEA, Gradle)
  70. 141.

    @ToddGinsberg Why Do I Use Kotlin? • 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. • Plays well with the tools I use (Spring, IDEA, Gradle) • Writing Kotlin, for me, is more fun.