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

Kotlin and why you should love it #1

Kotlin and why you should love it #1

Introductory slides about Kotlin

Roberto Orgiu

June 23, 2017
Tweet

More Decks by Roberto Orgiu

Other Decks in Programming

Transcript

  1. WHAT IS KOTLIN? > Compatible with JVM (and moar) >

    Made by Jetbrains > More expressive > Safer > Functional > Uses Extension Functions > Highly interoperable
  2. NULLABLE VS NONNULL > They are different types > Compile

    time error if you assign null to a non null variable > No more NullPointerException !
  3. NULLABLE VS NONNULL > val name: String = null ❌

    > val name: String = "Roberto" ✔ > val name: String? = null ✔
  4. NULLABLE VS NONNULL (INTEROPERABILITY) > Calling Java from Kotlin ➡

    Nullable > Unless it's annotated with @NonNull / @NotNull
  5. SMART CAST void function(Object something) { if(something instanceof String) {

    String s = (String) something; println(s.substring(0, 3)) } }
  6. DECLARING A CLASS class Person (name : String, surname :

    String?) { init { //code common to every constructor } }
  7. DECLARING A CLASS class Person (name : String, surname :

    String?) { constructor(name: String){ this(name, null) } init { //code common to every constructor } }
  8. DECLARING A CLASS class Person (name : String, surname :

    String? = null) { init { //code common to every constructor } }
  9. CALLING A METHOD ON A NULLABLE TYPE val p =

    Person("Pippo") val fifthCharOfSurname: Char? = p.surname?.charAt(4) //this is nullable type fifthCharOfSurname?.doSomething() //executed only if not null
  10. NULLABLE TYPES IN JAVA Person p = new Person("Pippo", null);

    String surname = p.getSurname(); if (surname != null) { Char fifthCharOfSurname = surname.charAt(4); if (fifthChar != null) { fifthCharOfSurname.doSomething(); } }
  11. VARIABLES > No implicit conversion: everything must be converted >

    Chars are not Ints, but we can convert them > Bitwise: | is or, & is and > Type can be inferred > Strings can be accessed as arrays
  12. VARIABLES val a = 42 a = 43 // No

    can do! var b = "hello" b = "ciao" // Yeah can do var c : Context = this
  13. VARIABLES class Person { var name : String = ""

    get() = field.toUppercase() set(value) { field = "Name: $value" } }
  14. when val type = when(fido) { is Dog -> "Dog"

    is Cat -> "Cat" else -> error("I only know about dogs and cats") }
  15. EXTENSION METHODS and how they are converted in Java static

    void bark(Dog dog) { ... } ExtensionKt.bark(pluto) ExtensionKt.bark(fido)
  16. INLINE FUNCTIONS they will be substituted by their code during

    compilation, instead of doing the real call to a function. inline fun <T> with(t: T, body: T.() -> Unit) { t.body() }
  17. HOW TO MAKE AN INLINE FUNCTION inline fun ifIsLollipop(code :

    () -> Unit) { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { code() } }