Upgrade to PRO for Only $50/Year—Limited-Time Offer! 🔥

Write Less Code with Kotlin and Spring Boot

Write Less Code with Kotlin and Spring Boot

As software developers, we aren't getting paid to write code; we're getting paid to deliver business value. Think of the last time you opened a codebase you weren't familiar with and had to wade through all of the boilerplate just to understand the core business logic or hunt down a critical bug. Less code means easier comprehension, quicker development, fewer bugs, and easier testing. Spring Boot is already very good at allowing us to deliver business quickly—why not take it to the next level with Kotlin? Kotlin has been described as a re-imagined Java. It's as if you took Java, fixed all of the things you didn't like about it, modernized the API, and made the result work seamlessly with your existing Java codebase. Combined with Spring Boot, Kotlin is a force multiplier for productivity and understanding.

This talk is aimed at Java and Spring Boot developers who might have heard of Kotlin but haven't tried it. You'll learn the basics of Kotlin and the features that make it compelling.

Todd Ginsberg

October 08, 2019
Tweet

More Decks by Todd Ginsberg

Other Decks in Technology

Transcript

  1. @ToddGinsberg Write Less Code with Kotlin and Spring Boot October

    7, 2019 Austin Convention Center Todd Ginsberg Principal Software Developer, Netspend
  2. @ToddGinsberg Agenda - What Is Kotlin? - Why Kotlin with

    Spring Boot? - Syntax & Features - Summary
  3. @ToddGinsberg Agenda - What Is Kotlin? - Why Kotlin with

    Spring Boot? - Syntax & Features - Summary - Questions?
  4. @ToddGinsberg Who is this Guy? Todd Ginsberg Just moved to

    Dallas from Chicago Principal Developer at Netspend - A payments company here in Austin! - We love Kotlin and Java!
  5. @ToddGinsberg What Is Kotlin? Statically typed language, developed by JetBrains

    Released under Apache 2.0 license Designed as a general purpose language
  6. @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
  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 6 or 8 bytecode • Targets ECMAScript 5.1
  8. @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
  9. @ToddGinsberg Major Features 100% Interoperable with Java Designed to avoid

    entire classes of defects Lots of small improvements that add up
  10. @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
  11. @ToddGinsberg The Hard Work is Already Done! - Kotlin Support

    since Spring Framework 5.0 - Nullability support between Java and Kotlin
  12. @ToddGinsberg The Hard Work is Already Done! - Kotlin Support

    since Spring Framework 5.0 - Nullability support between Java and Kotlin - Excellent documentation
  13. @ToddGinsberg The Hard Work is Already Done! - Kotlin Support

    since Spring Framework 5.0 - Nullability support between Java and Kotlin - Excellent documentation - Thorough examples
  14. @ToddGinsberg The Hard Work is Already Done! - Kotlin Support

    since Spring Framework 5.0 - Nullability support between Java and Kotlin - Excellent documentation - Thorough examples - Even better support being added for Spring Boot 2.2
  15. @ToddGinsberg Similar Philosophies “The goal of library design is to

    give application developers ready-to-use tools that cover their most frequent use-cases and solve the most popular problems. If something is needed all the time by any kind of application, it should be simple and straightforward to code. The correct code shall be the easiest one to write, while advanced, rarely needed corner-cases can and should take longer.”
  16. @ToddGinsberg Similar Philosophies “The goal of library design is to

    give application developers ready-to-use tools that cover their most frequent use-cases and solve the most popular problems. If something is needed all the time by any kind of application, it should be simple and straightforward to code. The correct code shall be the easiest one to write, while advanced, rarely needed corner-cases can and should take longer.” -- Roman Elizarov (JetBrains)
  17. @ToddGinsberg Less Code == More Room For Business Value -

    Less code means less cognitive load
  18. @ToddGinsberg Less Code == More Room For Business Value -

    Less code means less cognitive load - The most common case is the default
  19. @ToddGinsberg Less Code == More Room For Business Value -

    Less code means less cognitive load - The most common case is the default - Fewer places for bugs to hide
  20. @ToddGinsberg Less Code == More Room For Business Value -

    Less code means less cognitive load - The most common case is the default - Fewer places for bugs to hide - Work that you once had to do is a top level concern of the language / framework
  21. @ToddGinsberg Less Code == More Room For Business Value -

    Less code means less cognitive load - The most common case is the default - Fewer places for bugs to hide - Work that you once had to do is a top level concern of the language / framework - These effects stack
  22. @ToddGinsberg Variables and Values var place: String = "Austin" place

    = "Texas" // OK! val name: String = "Todd" name = "Emma" // Compile Error!
  23. @ToddGinsberg Equality val name1 = "EXAMPLE" val name2 = "example"

    // Structural Equality name1 == name2.toUpperCase() // True!
  24. @ToddGinsberg Equality val name1 = "EXAMPLE" val name2 = "example"

    // Structural Equality name1 == name2.toUpperCase() // True! // Referential Equality name1 === name2 // False!
  25. @ToddGinsberg Null Safety // Guaranteed to never be null var

    name: String = "Todd" // May be null var salary: Int? = null
  26. @ToddGinsberg Null-Safe Traversal var city: String? = "Austin" // Not

    allowed, might be null! city.toUpperCase() // Safe traversal city?.toUpperCase()
  27. @ToddGinsberg Elvis val lowest : Int? = listOf(1, 2, 3).min()

    val lowest : Int = listOf(1, 2, 3).min() ?: 0
  28. @ToddGinsberg Hey Kotlin, Hold My Beer! val lowest: Int? =

    listOf(1, 2, 3).min() val lowest: Int = listOf(1, 2, 3).min()!!
  29. @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()!!
  30. @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!
  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 Smart Casting when (x) { is Int -> print(x

    % 2 == 0) is String -> print(x.length + 1) is IntArray -> print(x.sum()) }
  33. @ToddGinsberg Smart Casting when (x) { is Int -> print(x

    % 2 == 0) is String -> print(x.length + 1) is IntArray -> print(x.sum()) }
  34. @ToddGinsberg Classes - Inheritance open class Entity : SomeInterface {

    // ... } class Customer : Entity() { // ... }
  35. @ToddGinsberg Properties public class Customer { private String name; public

    String getName() { return name; } public void setName(final String name) { this.name = name; } }
  36. @ToddGinsberg Properties class Customer { var name: String? = null

    } val c = Customer() c.name = "Todd" println("My name is ${c.name}")
  37. @ToddGinsberg Properties class Customer { var name: String? = null

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

    private set(value) { field = value?.toUpperCase() } }
  39. @ToddGinsberg Let’s Write a POJO! public class Person { public

    String firstName; public String lastName; }
  40. @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. @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. @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. @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. @ToddGinsberg Data Classes to the Rescue! data class Person(val firstName:

    String, val lastName: String) • Getters (and Setters for vars) as Properties
  45. @ToddGinsberg Data Classes to the Rescue! data class Person(val firstName:

    String, val lastName: String) • Getters (and Setters for vars) as Properties • toString()
  46. @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. @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. @ToddGinsberg Copying Data Classes val me = Person("Todd", "Ginsberg") val

    emma = me.copy(firstName = "Emma") // Person(”Emma", "Ginsberg")
  49. @ToddGinsberg Data Classes as @ConfigurationProperties @ConfigurationProperties("example.kotlin") data class KotlinExampleProperties( val

    name: String, val description: String = "Defaults Supported!", val myService: MyService ) data class MyService( val apiToken: String, val uri: URI )
  50. @ToddGinsberg Data Classes as @ConfigurationProperties @ConfigurationProperties("example.kotlin") data class KotlinExampleProperties( val

    name: String, val description: String = "Defaults Supported!", val myService: MyService ) data class MyService( val apiToken: String, val uri: URI ) Boot 2.2!
  51. @ToddGinsberg FUNctions! fun generateRandomNumber(): Int { return 4 } fun

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

    Int = offset + 4 random() // 4 random(1) // 5
  53. @ToddGinsberg FUNctions - Adding Parameters fun combine(first: Int, second: Int,

    third: Int = 0): Int = first + second + third combine(1, 2) combine(1, 2, 3)
  54. @ToddGinsberg FUNctions - Named Parameters fun combine(first: Int, second: Int):

    Int = first + second combine(first = 1, second = 2) // 3
  55. @ToddGinsberg FUNctions - Named Parameters fun combine(first: Int, second: Int):

    Int = first + second combine(second = 2, first = 1) // 3
  56. @ToddGinsberg The apply Extension // Single Expression val p =

    Person().apply { name = "Todd" age = 21 }
  57. @ToddGinsberg The apply Extension // Single Expression val p =

    Person().apply { name = "Todd" age = 21 address = Address().apply { line1 = "5 Tall Cedar Rd." … } }
  58. @ToddGinsberg One More Thing on FUNctions • Functions are final

    by default. • Arguments are always final.
  59. @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.
  60. @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.
  61. @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.
  62. @ToddGinsberg Lambdas listOf(1, 2, 3, 4) .filter { x ->

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

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

    2 == 0 } .map { it * 2 } // List[4, 8]
  65. @ToddGinsberg So Many Things Left Out! :( - Property delegation

    - Class delegation - Operator overloading - Destructuring - Higher-order functions - Companion objects - Import aliases - Type aliases - Unsigned integer types - Coroutines - Massive STDLIB replaces your util classes - Reified generics - Inline classes - Infix functions - Sealed classes - Scoping functions - DSL support
  66. @ToddGinsberg Why Do I Use Kotlin? • I write far

    less code. • The code I write is more expressive and clear.
  67. @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. @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. • Plays well with the tools I use (Spring, IDEA, Gradle)
  69. @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. • Plays well with the tools I use (Spring, IDEA, Gradle) • Writing Kotlin, for me, is more fun.
  70. @ToddGinsberg Fun == Fun % 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)
  71. @ToddGinsberg Fun == Fun % 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) Kotlin
  72. @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
  73. @ToddGinsberg Want to Learn More? The State of Kotlin Support

    in Spring Go back in time for this (or check it out on YouTube next week!)
  74. @ToddGinsberg Want to Learn More? Fully Reactive: Spring, Kotlin, and

    JavaFX Playing Together Today from 4:20pm–5:30pm In this room!
  75. @ToddGinsberg Want to Learn More? Klingon Kotlin (in Anger, er,

    Passion) with Project Reactor and Spring Boot: Ha' HIja'! Tomorrow from 11:30am–12:40pm In this room!