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

Kotlin for Java developers.

Hadi Tok
February 27, 2020

Kotlin for Java developers.

Hadi Tok

February 27, 2020
Tweet

More Decks by Hadi Tok

Other Decks in Programming

Transcript

  1. 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
  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. Why Kotlin? Concise Drastically reduce the amount of boilerplate code

    Source: kotlinlang.org /License: Apache 2.0
  8. 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
  9. Why Kotlin? Interoperable Leverage existing libraries for the JVM, Android,

    and the browser Source: kotlinlang.org /License: Apache 2.0
  10. fun sum(a: Int, b: Int): Int { return a +

    b } Source: kotlinlang.org /License: Apache 2.0
  11. 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
  12. 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
  13. 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
  14. class Request { void longRunningOperation(Callback callback) { String result =

    "result ok"; //assume long running callback.getResult(result); } interface Callback { void getResult(String result); } }
  15. val sum: (Int, Int) -> Int = { x: Int,

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

    y: Int -> x + y } sum(3,4) Source: kotlinlang.org /License: Apache 2.0
  17. val a: Int = 1 // immediate assignment val b

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

    += 1 Source: kotlinlang.org /License: Apache 2.0
  19. var a: String = "abc" a = null // compilation

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

    Source: kotlinlang.org /License: Apache 2.0
  21. val l: Int = a.length val m = b.length //

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

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

    println(a?.length) // Unnecessary safe call Source: kotlinlang.org /License: Apache 2.0
  24. 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
  25. val l = if (c != null) c.length else -1

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

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

    kotlinlang.org /License: Apache 2.0
  28. 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
  29. val s = "Hello, world!\n" val text = """ for

    (c in "foo") print(c) """ Source: kotlinlang.org /License: Apache 2.0
  30. 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
  31. if (obj is String) { // `obj` is automatically cast

    to `String` in // this branch return obj.length } Source: kotlinlang.org /License: Apache 2.0
  32. 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
  33. // `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
  34. val items = listOf("apple", "banana") for (item in items) {

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

    1..10 step 2) { print(x) } Source: kotlinlang.org /License: Apache 2.0
  36. 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
  37. 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
  38. 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
  39. 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
  40. class Person { var firstName: String var lastName: String constructor(firstName:

    String, lastName: String) { this.firstName = firstName this.lastName = lastName } }
  41. 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] } }
  42. 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; } }
  43. 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); } }
  44. 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 + '\'' + '}'; } }
  45. sealed class Result() data class Success(val value: String) : Result()

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

    // the else is not required because covered all the cases }
  47. val lazyValue: String by lazy { println("computed!") "Hello" } fun

    main() { println(lazyValue) println(lazyValue) } Source: kotlinlang.org /License: Apache 2.0
  48. 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
  49. 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");
  50. 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);
  51. String result = switch (0) { case 1, 2, 3

    -> "low"; case 4 -> "ok"; case 5, 6, 7 -> "high"; default -> "unknown"; }; System.out.println(result);
  52. String html = """ <html> <body> <p>Hello, world</p> </body> </html>

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

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

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

    Text Blocks • Pattern Matching for instanceof
  56. What is new with Java? Java 15 and later •

    Text Blocks • Pattern Matching for instanceof • Records
  57. record Person(String firstName, String lastName) { } Person p =

    new Person("Hadi", "Tok"); Source: http://openjdk.java.net/jeps/368
  58. 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
  59. 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