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

Kotlin for Java developers.

A6c0dcba5f373b33df2c2c55540faab1?s=47 Hadi Tok
February 27, 2020

Kotlin for Java developers.

A6c0dcba5f373b33df2c2c55540faab1?s=128

Hadi Tok

February 27, 2020
Tweet

Transcript

  1. Kotlin ve Java’nin yeni versiyonları Hadi Tok @hadi_tok Technical Lead

    @CitizenMe
  2. About Kotlin Kotlin is a cross-platform, statically typed, general-purpose programming

    language with type inference. Kotlin is designed to interoperate fully with Java. Kotlin mainly targets the JVM, but also compiles to JavaScript or native code. Source: wikipedia.org / License: WP:CC BY-SA
  3. About Kotlin Kotlin is a cross-platform, statically typed, general-purpose programming

    language with type inference. Kotlin is designed to interoperate fully with Java. Kotlin mainly targets the JVM, but also compiles to JavaScript or native code. Source: wikipedia.org / License: WP:CC BY-SA
  4. About Kotlin Kotlin is a cross-platform, statically typed, general-purpose programming

    language with type inference. Kotlin is designed to interoperate fully with Java. Kotlin mainly targets the JVM, but also compiles to JavaScript or native code. Source: wikipedia.org / License: WP:CC BY-SA
  5. About Kotlin Kotlin is a cross-platform, statically typed, general-purpose programming

    language with type inference. Kotlin is designed to interoperate fully with Java. Kotlin mainly targets the JVM, but also compiles to JavaScript or native code. Source: wikipedia.org / License: WP:CC BY-SA
  6. About Kotlin Kotlin is a cross-platform, statically typed, general-purpose programming

    language with type inference. Kotlin is designed to interoperate fully with Java. Kotlin mainly targets the JVM, but also compiles to JavaScript or native code. Source: wikipedia.org / License: WP:CC BY-SA
  7. About Kotlin Kotlin is a cross-platform, statically typed, general-purpose programming

    language with type inference. Kotlin is designed to interoperate fully with Java. Kotlin mainly targets the JVM, but also compiles to JavaScript or native code. Source: wikipedia.org / License: WP:CC BY-SA
  8. Why Kotlin? Concise Drastically reduce the amount of boilerplate code

    Source: kotlinlang.org /License: Apache 2.0
  9. Why Kotlin? Safe Avoid entire classes of errors such as

    null pointer exceptions Source: kotlinlang.org /License: Apache 2.0 Source: kotlinlang.org /License: Apache 2.0
  10. Why Kotlin? Interoperable Leverage existing libraries for the JVM, Android,

    and the browser Source: kotlinlang.org /License: Apache 2.0
  11. Kotlin for Java Programmers

  12. Functions

  13. fun main() { println("Hello world!") } Source: kotlinlang.org /License: Apache

    2.0
  14. fun sum(a: Int, b: Int): Int { return a +

    b } Source: kotlinlang.org /License: Apache 2.0
  15. fun sum(a: Int, b: Int): Int { return a +

    b } fun sum(a: Int, b: Int) = a + b Source: kotlinlang.org /License: Apache 2.0
  16. Default argumnets

  17. fun namePrinter(firstName: String, lastName: String) { print("$firstName $lastName") } namePrinter("Hadi",

    "Tok")
  18. fun namePrinter(firstName: String, lastName: String="Tok") { print("$firstName $lastName") } namePrinter("Hadi")

  19. Named argumnets

  20. fun namePrinter(firstName: String="Hadi", lastName: String="Tok") { print("$firstName $lastName") } namePrinter(lastName

    = "Hariri")
  21. infix notation

  22. class MyStringCollection { infix fun add(s: String) { /*...*/ }

    fun build() { this add "abc" // Correct add("abc") // Correct //add "abc" Incorrect: the receiver must be specified } } Source: kotlinlang.org /License: Apache 2.0
  23. Extension Functions

  24. fun MutableList<Int>.swap(index1: Int, index2: Int) { val tmp = this[index1]

    // 'this' corresponds to the list this[index1] = this[index2] this[index2] = tmp } Source: kotlinlang.org /License: Apache 2.0
  25. Higher Order Functions

  26. class Request { void longRunningOperation(Callback callback) { String result =

    "result ok"; //assume long running callback.getResult(result); } interface Callback { void getResult(String result); } }
  27. Request request =new Request(); request.longRunningOperation(new Callback() { @Override public void

    getResult(String result) { System.out.println(result); } });
  28. class Request{ fun longRunningOperation(callback:(String)->Unit){ val result = "result ok" //assume

    long running callback(result) } }
  29. val request= Request() request.longRunningOperation({result-> print(result) })

  30. val request= Request() request.longRunningOperation { result-> print(result) }

  31. val request = Request() request.longRunningOperation(this::printResult) fun printResult(result:String){ print(result) }

  32. Lambda expressions

  33. val sum: (Int, Int) -> Int = { x: Int,

    y: Int -> x + y } Source: kotlinlang.org /License: Apache 2.0
  34. val sum: (Int, Int) -> Int = { x: Int,

    y: Int -> x + y } sum(3,4) Source: kotlinlang.org /License: Apache 2.0
  35. Variables

  36. val a: Int = 1 // immediate assignment val b

    = 2 // `Int` type is inferred Source: kotlinlang.org /License: Apache 2.0
  37. var x = 5 // `Int` type is inferred x

    += 1 Source: kotlinlang.org /License: Apache 2.0
  38. Null Safety

  39. var a: String = "abc" a = null // compilation

    error Source: kotlinlang.org /License: Apache 2.0
  40. var b: String? = "abc" b = null // ok

    Source: kotlinlang.org /License: Apache 2.0
  41. val l: Int = a.length Source: kotlinlang.org /License: Apache 2.0

  42. val l: Int = a.length val m = b.length //

    error: variable 'b' can be null Source: kotlinlang.org /License: Apache 2.0
  43. val c: String? = null val l = if (c

    != null) c.length else -1 Source: kotlinlang.org /License: Apache 2.0
  44. val a = "Kotlin" val b: String? = null println(b?.length)

    println(a?.length) // Unnecessary safe call Source: kotlinlang.org /License: Apache 2.0
  45. val listWithNulls: List<String?> = listOf("Kotlin", null) for (item in listWithNulls)

    { item?.let { println(it) } //prints Kotlin and ignores null } Source: kotlinlang.org /License: Apache 2.0
  46. val l = if (c != null) c.length else -1

    Source: kotlinlang.org /License: Apache 2.0
  47. val l = if (c != null) c.length else -1

    val l = c?.length ?: -1 Source: kotlinlang.org /License: Apache 2.0
  48. var b: String? = "abc" val l = b!!.length Source:

    kotlinlang.org /License: Apache 2.0
  49. String Templates

  50. var a = 1 // simple name in template: val

    s1 = "a is $a" a = 2 // arbitrary expression in template: val s2 = "${s1.replace("is", "was")}, now is $a" Source: kotlinlang.org /License: Apache 2.0
  51. String Literals

  52. val s = "Hello, world!\n" Source: kotlinlang.org /License: Apache 2.0

  53. val s = "Hello, world!\n" val text = """ for

    (c in "foo") print(c) """ Source: kotlinlang.org /License: Apache 2.0
  54. val s = "Hello\nworld!" val text = """ for (c

    in "foo") print(c) """ val text = """ |Tell me and I forget. |Teach me and I remember. |Involve me and I learn. |(Benjamin Franklin) """.trimMargin() Source: kotlinlang.org /License: Apache 2.0
  55. Type checks and automatic casts

  56. if (obj is String) { // `obj` is automatically cast

    to `String` in // this branch return obj.length } Source: kotlinlang.org /License: Apache 2.0
  57. if (obj !is String) return null // `obj` is automatically

    cast to `String` in // this branch return obj.length Source: kotlinlang.org /License: Apache 2.0
  58. // `obj` is automatically cast to `String` on the //

    right-hand side of `&&` if (obj is String && obj.length > 0) { return obj.length } Source: kotlinlang.org /License: Apache 2.0
  59. Loops

  60. val items = listOf("apple", "banana") for (item in items) {

    println(item) } Source: kotlinlang.org /License: Apache 2.0
  61. for (x in 1..5) { print(x) } Source: kotlinlang.org /License:

    Apache 2.0
  62. for (x in 1..5) { print(x) } for (x in

    1..10 step 2) { print(x) } Source: kotlinlang.org /License: Apache 2.0
  63. for (x in 1..5) { print(x) } for (x in

    1..10 step 2) { print(x) } for (x in 9 downTo 0 step 3) { print(x) } Source: kotlinlang.org /License: Apache 2.0
  64. val items = listOf("apple", "banana") var index = 0 while

    (index < items.size) { println("item at $index is ${items[index]}") index++ } Source: kotlinlang.org /License: Apache 2.0
  65. when expression

  66. fun describe(obj: Any): String = when (obj) { 1 ->

    "One" "Hello" -> "Greeting" is Long -> "Long" !is String -> "Not a string" else -> "Unknown" } Source: kotlinlang.org /License: Apache 2.0
  67. Collections

  68. val fruits = listOf("banana", "avocado") fruits .filter { it.startsWith("a") }

    .sortedBy { it } .map { it.toUpperCase() } .forEach { println(it) } Source: kotlinlang.org /License: Apache 2.0
  69. Classes

  70. class Person { var firstName: String var lastName: String constructor(firstName:

    String, lastName: String) { this.firstName = firstName this.lastName = lastName } }
  71. class Person(var firstName: String, var lastName: String)

  72. val person = Person("Hadi", "Tok")

  73. Getter setter

  74. class Person(var firstName: String, var lastName: String){ var name =

    "$firstName $lastName" }
  75. class Person(var firstName: String, var lastName: String) { var name:

    String get() = "$firstName $lastName" }
  76. class Person(var firstName: String, var lastName: String) { var name:

    String get() = "$firstName $lastName" set(value) { val array = value.split(" ") firstName = array[0] lastName = array[1] } }
  77. Data Classes

  78. class Person { String firstName; String lastName; }

  79. class Person{ private String firstName; private String lastName; public String

    getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } }
  80. class Person{ private String firstName; private String lastName; public String

    getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; return Objects.equals(firstName, person.firstName) && Objects.equals(lastName, person.lastName); } @Override public int hashCode() { return Objects.hash(firstName, lastName); } }
  81. class Person{ private String firstName; private String lastName; public String

    getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; 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 + '\'' + '}'; } }
  82. class Person(var firstName: String, var lastName: String)

  83. data class Person(var firstName: String, var lastName: String)

  84. Sealed classes

  85. sealed class Result() data class Success(val value: String) : Result()

    data class Failure(val e: Exception) : Result()
  86. when(expr) { is Success -> println(result.value) is Failure -> println(result.e.message)

    // the else is not required because covered all the cases }
  87. Objects

  88. object PersonPrinter { fun printPerson(person: Person) { print(person.toString()) } }

  89. object PersonPrinter { fun printPerson(person: Person) { print(person.toString()) } }

    PersonPrinter.printPerson(Person("Hadi", "Tok"))
  90. Inline classes

  91. inline class Address(val value: String)

  92. inline class Address(val value: String) object AddressPrinter{ fun printAddress(address: Address){

    print(address.value) } }
  93. Delegated Properties

  94. val lazyValue: String by lazy { println("computed!") "Hello" } fun

    main() { println(lazyValue) println(lazyValue) } Source: kotlinlang.org /License: Apache 2.0
  95. Coroutines

  96. fun printer(){ GlobalScope.launch { val result = longRunningOperation() println("result is

    $result") } } suspend fun longRunningOperation(): String { delay(5000L) return "200" } Source: kotlinlang.org /License: Apache 2.0
  97. New Vesions of Java

  98. What is new with Java? Java 9 • Private methods

    in interfaces
  99. What is new with Java? Java 10 • var keyword

    (type inference)
  100. var a = "asd"; System.out.println(a);

  101. What is new with Java? Java 11 • Local Variable

    Syntax for Lambda Parameters
  102. interface LambdaInterface { abstract void doSomething(String x); } LambdaInterface lambdaInterface

    = ((String x) -> System.out.println(x) );
  103. interface LambdaInterface { abstract void doSomething(String x); } LambdaInterface lambdaInterface

    = ((var x) -> System.out.println(x) );
  104. What is new with Java? Java 12

  105. What is new with Java? Java 13

  106. What is new with Java? Java 14 • Switch Expressions

  107. String result = ""; int number = 0; switch (0)

    { case 1: case 2: case 3: result = "low"; break; case 4: result = "ok"; break; case 5: case 6: case 7: result = "high"; break; default: result ="unknown"; } System.out.println("result");
  108. String result ="" switch (0) { case 1,2,3: result =

    "low"; break; case 4: result = "ok"; break; case 5,6,7: result = "high"; break; default: result ="unknown"; } System.out.println(result);
  109. String result = switch (0) { case 1, 2, 3

    -> "low"; case 4 -> "ok"; case 5, 6, 7 -> "high"; default -> "unknown"; }; System.out.println(result);
  110. What is new with Java? Java 15 and later •

    Text Blocks
  111. String html = """ <html> <body> <p>Hello, world</p> </body> </html>

    """; Source: http://openjdk.java.net/jeps/368
  112. String html = """ <html> <body> <p>Hello, world</p> </body> </html>

    """; Source: http://openjdk.java.net/jeps/368
  113. String html = """ <html> <body> <p>Hello, world</p> </body> </html>

    """; Source: http://openjdk.java.net/jeps/368
  114. What is new with Java? Java 15 and later •

    Text Blocks • Pattern Matching for instanceof
  115. if(obj instanceof String){ String s = (String) obj; System.out.println(s); }

  116. if(obj instanceof String s){ System.out.println(s); }

  117. What is new with Java? Java 15 and later •

    Text Blocks • Pattern Matching for instanceof • Records
  118. record Person(String firstName, String lastName) { } Source: http://openjdk.java.net/jeps/368

  119. record Person(String firstName, String lastName) { } Person p =

    new Person("Hadi", "Tok"); Source: http://openjdk.java.net/jeps/368
  120. record Person(String firstName, String lastName) { } Person p =

    new Person("Hadi", "Tok"); System.out.println(p.firstName() + " " + p.lastName()); Source: http://openjdk.java.net/jeps/368
  121. Questions? Usefull Links • Kotlin web site: ◦ https://kotlinlang.org/ •

    Try Kotlin ◦ https://play.kotlinlang.org/ • KotlinConf 2019: What's New in Java 19: The end of Kotlin? by Jake Wharton : ◦ https://www.youtube.com/watch?v=te3OU9fxC8U
  122. Thank you! Hadi Tok @hadi_tok Technical Lead @CitizenMe