Kotlin - Not you grandfather's Java

Kotlin - Not you grandfather's Java

Introduction to Kotlin, for Java developers.

Presented on March 30th 2017 for the Portuguese Java User Group, at Talkdesk's Lisbon Office.

Eb987f4f2b2d43faa8b3b5a377713913?s=128

João Carvalho

March 30, 2017
Tweet

Transcript

  1. 2.
  2. 3.
  3. 4.
  4. 6.
  5. 7.
  6. 10.
  7. 11.
  8. 12.
  9. 14.
  10. 16.
  11. 17.

    public class HelloWorld { public static void main(String... args) {

    System.out .println("Hello world " + args[0]); } }
  12. 19.
  13. 22.
  14. 27.
  15. 28.
  16. 29.

    final String name = "Kotlin"; int age = 5; //

    A few moments later age = 6;
  17. 30.

    val name: String = "Kotlin" var age: Int = 5

    // A few moments later age = 6
  18. 31.

    val name = "Kotlin" var age = 5 // A

    few moments later age = 6
  19. 33.

    fun max(one: Int, other: Int): Int { if (one >

    other) { return one } else { return other } }
  20. 34.

    fun max(one: Int, other: Int): Int { return if (one

    > other) { one } else { other } }
  21. 35.

    fun max(one: Int, other: Int): Int = if (one >

    other) { one } else { other }
  22. 38.
  23. 39.

    when (x) { 1 -> print("x == 1") 2 ->

    print("x == 2") else -> { print("x is neither 1 nor 2") } }
  24. 46.

    fun printStringLength(any: Any) { if (any is String) { println("Length

    is ${any.length}") } else { return println("Oops, not a String") } }
  25. 47.

    fun printStringLength(any: Any) { val asString = any as String

    println("Length is ${asString.length}") }
  26. 48.

    fun printStringLength(any: Any) { val asString = any as? String

    println("Length is ${asString?.length ?: "Unknown"}") }
  27. 49.
  28. 54.

    class Fooer(name: String) { init { println("Setting up to foo

    $name") } constructor(name: String, option: String) : this(name) { println("\tUsing option $option") } }
  29. 72.

    @Override public boolean equals(Object o) { (Stuff generated by your

    IDE) } @Override public int hashCode() { int result = name.hashCode(); result = 31 * result + age; return result; }
  30. 73.
  31. 74.
  32. 85.
  33. 88.
  34. 92.

    emptyList() listOf(1, 2, 3) mutableListOf(1, 2, 3) emptySet() setOf("John", "Jane")

    mutableSetOf("John", "Jane") emptyMap() mapOf("John" to "Doe") mutableMapOf("John" to "Doe")
  35. 93.
  36. 94.

    // apply BaseClientDetails().apply { clientId = "foo" } // takeIf

    userRepository.findOne("foo")?.takeIf(User::active) // use inputStream.use { it.read() } // let clientId?.let { loadClient(it) }
  37. 97.

    fun <T> doWithinLock(lock: Lock, body: () -> T): T {

    lock.lock() try { return body() } finally { lock.unlock() } }
  38. 101.

    class HTML { var value = "" fun body(value: String)

    { this.value = value } } fun html(init: HTML.() -> Unit) = HTML().apply { init() } html { body("Hello world") }
  39. 102.