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

Kotlin as a Modernized Java @ Oracle Code One 2018

Kotlin as a Modernized Java @ Oracle Code One 2018

Kotlin was designed with Java developers in mind. Java is evolving, but the language evolution is mostly limited to adding new features. It is nearly impossible to remove features that have proved to be troublesome from a language as popular as Java. This session looks at those features that have been either removed or radically adjusted in Kotlin and how this leads to better, modern, easier-to-read code in Kotlin while still retaining the ability to leverage all the Java libraries in the Java ecosystem.

F9c354e780ce562daea0e21b99bfdc0d?s=128

Roman Elizarov

October 25, 2018
Tweet

More Decks by Roman Elizarov

Other Decks in Programming

Transcript

  1. Kotlin as a Modernized Java Programming in XXI Century Presented

    at JavaOne, 2018 email elizarov@ Roman Elizarov @relizarov
  2. 1995 2003 2004 2011

  3. What if Java was designed in 201x?

  4. Error handling

  5. Error handling int res = fread(buf, n, file);

  6. Error handling int res = fread(buf, n, file); if (res

    < n) { // error or EOF if (ferror(file) != 0) { // handle error } return; }
  7. Error handling int res = fread(buf, n, file); if (res

    < n) { … } res = fread(buf, m, file); if (res < n) { // error or EOF if (ferror(file) != 0) { // handle error } return; }
  8. Exceptions try { FileInputStream file = new FileInputStream(fileName); // …

    int res = file.read(buf, 0, n); // throws exception // … } catch (IOException e) { // handle error }
  9. Exceptions try { FileInputStream file = new FileInputStream(fileName); // …

    int res = file.read(buf, 0, n); // … res = file.read(buf, 0, m); // throws exception // … } catch (IOException e) { // handle error }
  10. Exceptions try { Data result = work(fileName); } catch (IOException

    e) { // handle error }
  11. Checked Exceptions Data work(String fileName) throws IOException { FileInputStream file

    = new FileInputStream(fileName); // … int res = file.read(buf, 0, n); // … res = file.read(buf, 0, m); // … }
  12. None
  13. 1995 1.0 2004 5 Generics

  14. 1995 1.0 2004 5 Generics Lambdas (FP) 2014 8

  15. Imperative List<Result> results = new ArrayList<>(); for (String fileName :

    fileNames) { Result work = work(fileName); results.add(work); }
  16. Func%onal & Declara%ve List<Result> results = fileNames.stream() .map(fileName -> work(fileName))

    .collect(Collectors.toList());
  17. Functional + Checked Exceptions = ! List<Result> results = fileNames.stream()

    .map(fileName -> work(fileName)) .collect(Collectors.toList());
  18. XXI Century Languages 2000 2003 2005 2004 2009 2010 2011

    2011 2012 2014
  19. If Java was designed in 201x It would not have

    checked exceptions
  20. Func%onal

  21. Functional in Java List<Result> results = fileNames.stream() .map(fileName -> work(fileName))

    .collect(Collectors.toList());
  22. Functional in Java as an afterthought List<Result> results = fileNames.stream()

    .map(fileName -> work(fileName)) .collect(Collectors.toList());
  23. Kotlin is designed to be functional val results = fileNames

    .map { fileName -> work(fileName) }
  24. val results = fileNames .map { work(it) }

  25. val results = fileNames .map { work(it) } .filter {

    it.isGood() }
  26. val results = fileNames .map { work(it) } .filter {

    it.isGood() } .doMyProcessing()
  27. val results = fileNames .map { work(it) } .filter {

    it.isGood() } .doMyProcessing()
  28. val results = MyUtils.doMyProcessing(fileNames .map { work(it) } .filter {

    it.isGood() })
  29. val results = fileNames .map { work(it) } .filter {

    it.isGood() } .doMyProcessing()
  30. Kotlin extension functions val results = fileNames .map { work(it)

    } .filter { it.isGood() } .doMyProcessing() fun List<Data>.doMyProcessing() = …
  31. Kotlin top-level functions val results = fileNames .map { work(it)

    } .filter { it.isGood() } .doMyProcessing() fun List<Data>.doMyProcessing() = …
  32. If Java was designed in 201x It would have been

    functional by design
  33. More generic casualties…

  34. More generic casualties… List<String> strings = …

  35. More generic casualties… List<String> strings = … List<Date> dates =

  36. More generic casualties… List<String> strings = … List<Date> date =

    … List<int> ints = …
  37. More generic casualties… List<String> strings = … List<Date> date =

    … List<Integer> ints = …
  38. Primitives

  39. C for Consistency myDate.toString()

  40. C for Consistency myDate.toString() String.valueOf(myInt)

  41. Equality myInt == otherInt

  42. Equality myInt == otherInt myString == otherString Oops!

  43. Equality myInt == otherInt myString.equals(otherString)

  44. If Java was designed in 201x It would not have

    exposed primitives
  45. Kotlin hides primi/ves myDate.toString() myInt.toString()

  46. Kotlin hides primitives myDate.toString() myInt.toString() List<Date> List<Int>

  47. Kotlin hides primitives myDate.toString() myInt.toString() List<Date> List<Int> dates.map { it.toString()

    } ints.map { it.toString() }
  48. Kotlin hides primitives myDate.toString() myInt.toString() List<Date> List<Int> dates.map { it.toString()

    } ints.map { it.toString() } myDate == otherDate myInt == otherInt
  49. Local variable type inference 1995 1.0 2004 5 2018 10

    2014 8
  50. Before type inference int count = … double average =

    … List<String> strings = … Map<Warehouse, List<OrderItem>> items = …
  51. With type inference var count = … var average =

    … var strings = … var items = …
  52. With type inference var count = … var average =

    … var strings = … Map<Warehouse, List<OrderItem>> items = …
  53. Types on right! var count = … var average =

    … var strings = … var items: Map<Warehouse, List<OrderItem>> = …
  54. Where is the type in XXI Century? Left Right

  55. Where is the type in XXI Century? Left Right

  56. If Java was designed in 201x It would have been

    designed for type inference with types on the right
  57. Type safety

  58. How type-safe is that? int process(List input) { … }

  59. How type-safe is that? int process(List<Data> input) { … }

  60. How type-safe is that? int process(List<Data> input) { … }

    process(null); Oops!
  61. Null in Kotlin fun process(input: List<Data>): Int { … }

    process(null)
  62. Null in Kotlin is forbidden by default fun process(input: List<Data>):

    Int { … } process(null)
  63. Opt-in to use nulls fun process(input: List<Data>?): Int { …

    } process(null)
  64. fun process(input: List<Data>?): Int { … return input.size } process(null)

  65. fun process(input: List<Data>?): Int { … return input.size } process(null)

  66. fun process(input: List<Data>?): Int { … return input?.size } process(null)

  67. fun process(input: List<Data>?): Int { … return input?.size } process(null)

  68. fun process(input: List<Data>?): Int? { … return input?.size } process(null)

  69. If Java was designed in 201x It would have had

    null-safety
  70. How type-safe is that? int process(List<Data> input) { … }

  71. How type-safe is that? int process(List<Data> input) { input.removeIf(data ->

    !data.isGood()); return input.size(); }
  72. How type-safe is that? int process(List<Data> input) { input.removeIf(data ->

    !data.isGood()); return input.size(); } Oops!
  73. Collections in Kotlin fun process(input: List<Data>): Int { input.removeIf {

    data -> !data.isGood() } return input.size }
  74. Collections in Kotlin are read-only fun process(input: List<Data>): Int {

    input.removeIf { data -> !data.isGood() } return input.size }
  75. Opt-in to mutability fun process(input: MutableList<Data>): Int { input.removeIf {

    data -> !data.isGood() } return input.size }
  76. How type-safe is that? int process(List<Data> input) { … int

    size = input.size(); … return size; }
  77. How type-safe is that? int process(List<Data> input) { … final

    int size = input.size(); … return size; }
  78. Kotlin: Make val not var fun process(input: List<Data>): Int {

    … val size = input.size … return size }
  79. Choice of Defaults

  80. Defaults Null/Not-null

  81. Defaults Java Null/Not-null Nullable

  82. Defaults Java Real life Null/Not-null Nullable Non-nullable

  83. Defaults Java Real life Null/Not-null Nullable Non-nullable Mutable/Immutable

  84. Defaults Java Real life Null/Not-null Nullable Non-nullable Mutable/Immutable Mutable

  85. Defaults Java Real life Null/Not-null Nullable Non-nullable Mutable/Immutable Mutable Immutable

  86. Defaults Java Real life Null/Not-null Nullable Non-nullable Mutable/Immutable Mutable Immutable

    Open/Final
  87. Defaults Java Real life Null/Not-null Nullable Non-nullable Mutable/Immutable Mutable Immutable

    Open/Final Open
  88. Defaults Java Real life Null/Not-null Nullable Non-nullable Mutable/Immutable Mutable Immutable

    Open/Final Open Final
  89. Defaults Java Real life Null/Not-null Nullable Non-nullable Mutable/Immutable Mutable Immutable

    Open/Final Open Final Private/Public
  90. Defaults Java Real life Null/Not-null Nullable Non-nullable Mutable/Immutable Mutable Immutable

    Open/Final Open Final Private/Public Pkg private
  91. Defaults Java Real life Null/Not-null Nullable Non-nullable Mutable/Immutable Mutable Immutable

    Open/Final Open Final Private/Public Pkg private Public
  92. If Java was designed in 201x It would have very

    different defaults
  93. Syntax

  94. Semicolon foo(); bar();

  95. Semicolon foo(); bar();

  96. Semicolon foo(); bar();

  97. Semicolon foo() bar()

  98. Where is the semicolon in XXI Century? Mandatory None/Optional

  99. Where is the semicolon in XXI Century? Mandatory None/Optional

  100. If Java was designed in 201x It would have optional

    semicolon
  101. What if Java was designed in 201x? ØNo checked exceptions

    ØDesigned for type inference ØFunctional by design ØNo exposed primitives ØNull safety ØWell-founded defaults ØOptional semicolon
  102. Syntactic sugar

  103. Properties in Java public class Person { private String firstName;

    private String lastName; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } …
  104. Properties in Kotlin class Person { var firstName: String? =

    null var lastName: String? = null }
  105. Primary constructor in Java public class Person { private String

    firstName; private String lastName; public Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } …
  106. Primary constructor in Kotlin class Person( var firstName: String?, var

    lastName: String? )
  107. Primary constructor + null-safety = ❤ class Person( var firstName:

    String, var lastName: String )
  108. Equals/hashCode/etc in Java public class Person { private String firstName;

    private String lastName; @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Person)) return false; Person person = (Person) o; return Objects.equals(firstName, person.firstName) && Objects.equals(lastName, person.lastName); } …
  109. Data class in Kotlin data class Person( var firstName: String,

    var lastName: String )
  110. String concatenation in Java public class Person { @Override public

    String toString() { return firstName + " " + lastName; } …
  111. String format in Java public class Person { @Override public

    String toString() { return String.format("%s %s", firstName, lastName); } …
  112. String interpolation in Kotlin class Person(…) { override fun toString():

    String { return "$firstName $lastName"; } …
  113. String interpolation in Kotlin class Person(…) { override fun toString():

    String = "$firstName $lastName" …
  114. Singleton in Java public class Singleton { public static final

    INSTANCE = new Singleton(); private Singleton() {} … }
  115. Singleton in Kotlin object Singleton { … }

  116. Why Kotlin?

  117. Kotlin was designed as a modernized Java

  118. Kotlin ØInteroperability with JVM ecosystem ØEasy to learn for Java

    developers by design ØExtensible, DSL-friendly ØPragmatic ØFun to work with
  119. Resources Økotlinlang.org Øtry.kotlinlang.org Ødiscuss.kotlinlang.org Øslack.kotlinlang.org

  120. Thank you Any questions? Slides are available at https://speakerdeck.com/elizarov email

    elizarov@ Roman Elizarov @relizarov