Is Kotlin Right For You? - Oracle Code Chicago 2018

Is Kotlin Right For You? - Oracle Code Chicago 2018

Sure Java pays the bills for some of us, but there’s no reason why we can’t have fun developing again. Kotlin, developed by JetBrains, has been catching on lately because of its functional nature, null safety, 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?

In this session we will go over what Kotlin is, what problems it solves, and what makes it stand out from other JVM languages. You’ll come away with enough knowledge to decide if this is something you and your team should consider adopting.

2777430c1f9869e411ab5d8b17d8ba2a?s=128

Todd Ginsberg

March 20, 2018
Tweet

Transcript

  1. 1.

    Is Kotlin Right For You? Oracle Code Chicago 2018 Todd

    Ginsberg Principal Software Developer @ToddGinsberg
  2. 2.

    @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 CFO
  3. 3.

    @ToddGinsberg Safe Harbor Statement By Editors of Open Street Map

    - Open Street Map, CC BY-SA Kotlin Island
  4. 7.

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

    JetBrains Released under Apache 2.0 license JVM 6 or 8 bytecode Also targets ECMAScript 5.1 LLVM compiler can compile to native
  5. 8.

    @ToddGinsberg Major Features 100% interoperable with Java Very easy to

    learn Type Inference More than diamond operator or local var (thanks Java 10!) Null-safe 168,000+ issues on GitHub! 10,579 duplicates on Stack Overflow! Fantastic IDE support Large, positive community
  6. 11.

    @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
  7. 14.

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

    = "Illinois" // OK! val name: String = "Todd" name = "Emma" // Compile Error!
  8. 16.
  9. 17.

    @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
  10. 19.

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

    name: String = "Todd" // May be null val salary: Int? = null
  11. 20.

    @ToddGinsberg var city: String? = "Chicago" // Not allowed, might

    be null! city.toUpperCase() // Safe traversal city?.toUpperCase() Null-safe Traversal
  12. 21.

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

    lowest : Int = listOf(1, 2, 3).min() ?: 0 Elvis
  13. 23.

    @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
  14. 26.

    @ToddGinsberg Classes - Inheritance open class Entity : SomeInterface {

    // ... } class Customer : Entity() { // ... }
  15. 27.

    @ToddGinsberg Classes - Construction class Entity(type: String) { val description

    = "$type Entity" init { println("I am constructing a $type Entity") } }
  16. 28.

    @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"
  17. 29.

    @ToddGinsberg Properties – Get/Set class Customer(var name: String) { var

    state: String? = null set(value) { field = value?.toUpperCase() } }
  18. 30.

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

    String firstName; public String lastName; }
  19. 31.

    @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; } }
  20. 32.

    @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; } }
  21. 33.

    @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); } }
  22. 34.

    @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 + '\'' + '}'; } }
  23. 35.

    @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…
  24. 36.

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

    emma = me.copy(firstName = "Emma") // Person(”Emma", "Ginsberg")
  25. 37.

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

    (first, last) = me // first == “Todd” last == “Ginsberg”
  26. 38.
  27. 40.

    @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” parseString(s) -> "the same as parseString” else -> "x doesn't match anything" }
  28. 41.

    @ToddGinsberg when (x) { is Int -> print(x % 2

    == 0) is String -> print(x.length + 1) is IntArray -> print(x.sum()) else -> println("Unhandled Type") } if(x != null) { println(x.toString()) } Smart Casting
  29. 42.

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

    generateRandomNumber(): Int = 4 fun generateRandomNumber() = 4
  30. 43.

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

    Int = offset + 4 random() // 4 random(1) // 5
  31. 44.

    @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
  32. 45.

    @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
  33. 46.

    @ToddGinsberg fun measureTimeMillis(block: () -> Unit): Long { val start

    = System.currentTimeMillis() block() return System.currentTimeMillis() - start } val time = measureTimeMillis { someSlowQuery() } High Order FUNctions
  34. 47.

    @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!
  35. 49.

    @ToddGinsberg What About Static? class MyClass { companion object {

    fun fromDto(dto: MyClassDto): MyClass = // Create logic here... } } // Elsewhere… val instance = MyClass.fromDto(someDto)
  36. 50.

    @ToddGinsberg What About Static? object Constants { val PREFIX_CODE =

    16309 } // Elsewhere… transmit(Constants.PREFIX_CODE) Can include functions Can implement interfaces
  37. 51.

    @ToddGinsberg One More Thing On FUNctions… Functions are final by

    default. Functions can be defined in a file, outside of a class. Functions can be defined within another function. Kotlin supports tail recursive functions.
  38. 52.

    @ToddGinsberg Apply What You’ve Learned // Expression and Statements val

    p = Person() p.name = "Todd" p.age = 21 // Single Expression val p = Person().apply { name = "Todd" age = 21 }
  39. 53.

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

    % 2 == 0 } .map { y -> y * 2 } // List[4, 8] Lambdas
  40. 54.

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

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

    @ToddGinsberg Lambdas Are Closures val ints = listOf(1, 2, 3,

    4) var sum = 0 ints.forEach { sum += it } println(sum) // 10
  42. 56.

    @ToddGinsberg Operators 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)
  43. 57.

    @ToddGinsberg Operators Limited overloading – cannot define your own operators.

    Expression Translated to a in b b.contains(a) a !in b !b.contains(a)
  44. 58.

    @ToddGinsberg Operators Limited overloading – cannot define your own operators.

    Expression Translated to a[i] a.get(i) a[i] = b a.set(i, b)
  45. 59.

    @ToddGinsberg Operators 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)
  46. 60.

    @ToddGinsberg Operators 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
  47. 62.

    @ToddGinsberg // Thanks type erasure L fun <T> loggerOf(): Logger

    = Logger.getLogger(T::class.java) Reified Generics
  48. 65.

    @ToddGinsberg Community Resources https://kotlinlang.slack.com • 15,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
  49. 69.

    @ToddGinsberg Why Kotlin is Right For Me I write far

    less code. The code I write is more expressive and clear. 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)