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. Kotlin ve Java’nin yeni
    versiyonları
    Hadi Tok
    @hadi_tok
    Technical Lead @CitizenMe

    View Slide

  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

    View Slide

  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

    View Slide

  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

    View Slide

  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

    View Slide

  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

    View Slide

  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

    View Slide

  8. Why Kotlin?
    Concise
    Drastically reduce the amount of boilerplate code
    Source: kotlinlang.org /License: Apache 2.0

    View Slide

  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

    View Slide

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

    View Slide

  11. Kotlin for Java
    Programmers

    View Slide

  12. Functions

    View Slide

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

    View Slide

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

    View Slide

  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

    View Slide

  16. Default argumnets

    View Slide

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

    View Slide

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

    View Slide

  19. Named argumnets

    View Slide

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

    View Slide

  21. infix notation

    View Slide

  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

    View Slide

  23. Extension Functions

    View Slide

  24. fun MutableList.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

    View Slide

  25. Higher Order Functions

    View Slide

  26. class Request {
    void longRunningOperation(Callback callback) {
    String result = "result ok"; //assume long running
    callback.getResult(result);
    }
    interface Callback {
    void getResult(String result);
    }
    }

    View Slide

  27. Request request =new Request();
    request.longRunningOperation(new Callback() {
    @Override
    public void getResult(String result) {
    System.out.println(result);
    }
    });

    View Slide

  28. class Request{
    fun longRunningOperation(callback:(String)->Unit){
    val result = "result ok" //assume long running
    callback(result)
    }
    }

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  32. Lambda expressions

    View Slide

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

    View Slide

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

    View Slide

  35. Variables

    View Slide

  36. val a: Int = 1 // immediate assignment
    val b = 2 // `Int` type is inferred
    Source: kotlinlang.org /License: Apache 2.0

    View Slide

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

    View Slide

  38. Null Safety

    View Slide

  39. var a: String = "abc"
    a = null // compilation error
    Source: kotlinlang.org /License: Apache 2.0

    View Slide

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

    View Slide

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

    View Slide

  42. val l: Int = a.length
    val m = b.length // error: variable 'b' can be null
    Source: kotlinlang.org /License: Apache 2.0

    View Slide

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

    View Slide

  44. val a = "Kotlin"
    val b: String? = null
    println(b?.length)
    println(a?.length) // Unnecessary safe call
    Source: kotlinlang.org /License: Apache 2.0

    View Slide

  45. val listWithNulls: List = listOf("Kotlin", null)
    for (item in listWithNulls) {
    item?.let { println(it) } //prints Kotlin and ignores null
    }
    Source: kotlinlang.org /License: Apache 2.0

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  49. String Templates

    View Slide

  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

    View Slide

  51. String Literals

    View Slide

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

    View Slide

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

    View Slide

  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

    View Slide

  55. Type checks and automatic
    casts

    View Slide

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

    View Slide

  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

    View Slide

  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

    View Slide

  59. Loops

    View Slide

  60. val items = listOf("apple", "banana")
    for (item in items) {
    println(item)
    }
    Source: kotlinlang.org /License: Apache 2.0

    View Slide

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

    View Slide

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

    View Slide

  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

    View Slide

  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

    View Slide

  65. when expression

    View Slide

  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

    View Slide

  67. Collections

    View Slide

  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

    View Slide

  69. Classes

    View Slide

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

    View Slide

  71. class Person(var firstName: String, var lastName: String)

    View Slide

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

    View Slide

  73. Getter setter

    View Slide

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

    View Slide

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

    View Slide

  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]
    }
    }

    View Slide

  77. Data Classes

    View Slide

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

    View Slide

  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;
    }
    }

    View Slide

  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);
    }
    }

    View Slide

  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 + '\'' +
    '}';
    }
    }

    View Slide

  82. class Person(var firstName: String, var lastName: String)

    View Slide

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

    View Slide

  84. Sealed classes

    View Slide

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

    View Slide

  86. when(expr) {
    is Success -> println(result.value)
    is Failure -> println(result.e.message)
    // the else is not required because covered all the cases
    }

    View Slide

  87. Objects

    View Slide

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

    View Slide

  89. object PersonPrinter {
    fun printPerson(person: Person) {
    print(person.toString())
    }
    }
    PersonPrinter.printPerson(Person("Hadi", "Tok"))

    View Slide

  90. Inline classes

    View Slide

  91. inline class Address(val value: String)

    View Slide

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

    View Slide

  93. Delegated Properties

    View Slide

  94. val lazyValue: String by lazy {
    println("computed!")
    "Hello"
    }
    fun main() {
    println(lazyValue)
    println(lazyValue)
    }
    Source: kotlinlang.org /License: Apache 2.0

    View Slide

  95. Coroutines

    View Slide

  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

    View Slide

  97. New Vesions of Java

    View Slide

  98. What is new with Java?
    Java 9
    ● Private methods in interfaces

    View Slide

  99. What is new with Java?
    Java 10
    ● var keyword (type inference)

    View Slide

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

    View Slide

  101. What is new with Java?
    Java 11
    ● Local Variable Syntax for Lambda Parameters

    View Slide

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

    View Slide

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

    View Slide

  104. What is new with Java?
    Java 12

    View Slide

  105. What is new with Java?
    Java 13

    View Slide

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

    View Slide

  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");

    View Slide

  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);

    View Slide

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

    View Slide

  110. What is new with Java?
    Java 15 and later
    ● Text Blocks

    View Slide

  111. String html = """


    Hello, world


    """;
    Source: http://openjdk.java.net/jeps/368

    View Slide

  112. String html = """


    Hello, world


    """;
    Source: http://openjdk.java.net/jeps/368

    View Slide

  113. String html = """


    Hello, world


    """;
    Source: http://openjdk.java.net/jeps/368

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  117. What is new with Java?
    Java 15 and later
    ● Text Blocks
    ● Pattern Matching for instanceof
    ● Records

    View Slide

  118. record Person(String firstName, String lastName) {
    }
    Source: http://openjdk.java.net/jeps/368

    View Slide

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

    View Slide

  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

    View Slide

  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

    View Slide

  122. Thank you!
    Hadi Tok
    @hadi_tok
    Technical Lead @CitizenMe

    View Slide