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

hands-on-kotlin

 hands-on-kotlin

Hands On Kotlin Presentation
Kotlin Yorkshire Meetup Group
20 April, 2017

Andy Bowes

April 20, 2017
Tweet

More Decks by Andy Bowes

Other Decks in Technology

Transcript

  1. 0. Purpose of Evening Quick introduction to Kotlin An opportunity

    to get your hands dirty with a safety net
  2. “ I hear and I forget. I see and I

    remember. I do and I understand. Confucius
  3. Basic Data Types ◎ Similar to Java ◎ Numeric: ◦

    Int, Long, Float, Double, Short, Byte ◎ Text ◦ String, Char ◎ Other ◦ Boolean ◦ Any - Root class in hierarchy ≈ Java Object ◦ Nothing In Kotlin, everything is an Object, there are no primitive types i.e. int, double, etc
  4. Null Safety ◎ Kotlin attempts to eliminate Null Pointer Exceptions.

    ◎ By default, Kotlin variables/parameters will not accept Nulls ◎ Identify nullable values with a ‘?’ on datatype. ◦ E.g. Int? Or String? ◦ similar to Java Optional or Scala Option
  5. Null Safety - Part 2 ◎ var a: String =

    "abc" a = null // compilation error, doesn’t allow null var b: String? = "abc" b = null // ok val l = b.length // error: 'b' can be null val l = b?.length // gives length or null // ‘Elvis’ operator val l = b?.length ?: -1 // gives length or -1 // Null checks can be chained together bob?.department?.head?.name val l = b!!.length // Throws NPE if b is null
  6. Smart Casting ◎ Kotlin reduces the need to perform manual

    casting of variables. ◎ if (obj is String) { print(obj.length) // obj has been cast to String } ◎ // Automatically cast or right-side of && check if (x is String && x.length > 0) { print(x.length) } ◎ // When clauses when (x) { is Int -> print(x + 1) is String -> print(x.length + 1) is IntArray -> print(x.sum()) }
  7. Safe Casting ◎ Manual casting is still permitted. val x:

    String = y as String // Will fail if y is null val x: String? = y as String? // Will handle null values ◎ Can improve handling using Safe Casting ‘as?’ to avoid ClassCastExceptions. ◎ // returns a String or null if y is not a String val x: String? = y as? String
  8. Control Flow - if condition ◎ if (condition) .. else

    .. ◎ Returns a value & so can be used as an expression. ◦ val totalValue = if (discountSelected) value * 0.85 else value ◎ Used as a ternary operator ◎ More complex expression blocks can be enclosed in braces {}. Last statement in each block provides the returned value.
  9. Control Flow - when expression ◎ Similar to Java switch

    statement but even more powerful. Close to Scala pattern matching. ◎ Can select branch on: ◦ The value of an argument. ◦ The type of an argument ◦ An expression ◎ Default option is supplied by an ‘else’ condition. ◎ ‘when’ is an expression like ‘if’ and returns a result.
  10. Control Flow - when examples ◎ Branch by Value when

    (x) { 1 -> print("x == 1") 2 -> print("x == 2") else -> { // Note the block print("x is neither 1 nor 2") } } ◎ Branch by Type val hasPrefix = when(x) { is String -> x.startsWith("prefix") else -> false } ◎ If.. Else If .. replacement when { x.isOdd() -> print("x is odd") x.isEven() -> print("x is even") else -> print("x is funny") }
  11. Control Flow - For loops ◎ Iterate through items in

    a Collection (or anything that supplies an Iterator) ◎ Body of loop can be a single operation or a code block. ◎ Can supply numeric ranges ◦ for (i in 1..10) { println(i) } ◦ for (i in 1..4 step 2) print(i) ◦ for (i in 4 downTo 1 step 2) print(i)
  12. Control Flow - While loops ◎ While loops are exactly

    like Java ◎ while (x > 0) { x-- } ◎ do { val y = readLine() } while (y != null)
  13. Function Definitions ◎ Functions can be declared inside or outside

    a Class. ◎ Local Functions can be declared inside another function. ◎ Parameters defined as name: type and separated by commas. ◎ Return types are optional (inferred) if function is a single expression but must be specified if function has a code block. ◎ ‘Unit’ return type is equivalent of Java ‘void’ but this is optional
  14. Function Definitions - Parameters ◎ Parameters can be passed by

    name ◦ reformat(str, ◦ normalizeCase = true, ◦ divideByCamelHumps = false, ◦ wordSeparator = '_' ) ◎ Parameters can have default values ◦ fun read(b: Array<Byte>, off: Int = 0, len: Int = b.size()) { ◦ ... ◦ } ◎ Default values reduces the need to create overloaded methods.
  15. Extension Functions ◎ Allows you to add functions to a

    Class without needing to subclass it. ◎ Can add functions to any Class even core Java classes. ◎ NB - Does not allow you to override existing methods. ◎ Provides a cleaner, more functional alternative to Java Utility classes with static methods.
  16. Extension Functions (examples) ◎ fun String.toCamelCase() : String { return

    this.split(' ').map { it -> it.toLowerCase().capitalize() }.joinToString(separator = "") } ◎ fun MutableList<Int>.swap(index1: Int, index2: Int) { val tmp = this[index1] this[index1] = this[index2] this[index2] = tmp }
  17. Lambda Expressions ◎ Lambda Expressions are blocks of code that

    optionally take parameters. ◎ Allow the code to be executed at a later point in time. ◎ Can be assigned to variables, passed as parameters and returned from functions.
  18. Lambda Expressions - examples ◎ val sum: (Int, Int) ->

    Int = { x, y -> x + y } Simplified by removing inferred return type: val sum = { x: Int, y: Int -> x + y } ◎ Lambda can then be later invoked val total = sum(12, 19) ◎ If the lambda function only has 1 parameter it does not need to be declared but can be accessed by implicit name of ‘it’. orders.filter{ it.value > 100}
  19. Class Declaration ◎ Classes are defined with key word ‘class’

    class Person constructor(firstName: String) {} ◎ Many classes can be defined in same file & name of the file does not need to match the class name. ◎ Each class has 1 primary constructor & may optionally have multiple secondary constructors. ◎ Instances of classes are created by calling constructor as if it was just a function. val customer = Customer("Joe Smith") ◎ By default, Kotlin classes are ‘final’. If you want a class to allows sub-classes it needs to be defined as ‘open’. open class Base(p: Int)
  20. Class Parameters & Properties ◎ Constructors can have parameters defined

    just like a standard method. class Person constructor(firstName: String) {} ◎ These parameters are treated as properties if they are proceeded by ‘val’ or ‘var’. class Person(val firstName: String, val lastName: String, var age: Int) { // ...}
  21. Data Classes ◎ Built in Support for Java Bean/ DTO

    classes. data class User(val name: String, val age: Int) ◎ Automatically generates the following methods at compile time: ◦ getter/setter for each property ◦ equals ◦ hashCode ◦ toString ◎ Dramatically reduces the amount of boilerplate code, even if that can be generated by the IDE.
  22. Class Inheritance ◎ All classes extend the Any base class

    ◎ To explicitly extend another class need to pass parameters to parent constructor open class Person(firstName: String, surname: String) class Customer(accountNo: String,firstName: String, surname: String) : Person(firstName, surname) ◎ To override a method it must be declared as ‘open’ in the parent class & must be explicitly overriden. open class Base { open fun v() {} fun nv() {} } class Derived() : Base() { override fun v() {} }
  23. Companion Objects ◎ Kotlin does not permit the creation of

    static methods on a Class. ◎ Can define Companion Objects within standard classes. class MyClass { companion object Factory { fun create(): MyClass = MyClass() } } val myInstance = MyClass.Factory.create()
  24. Singleton Objects ◎ Singletons can be created using top-level object

    definitions (i.e. outside of a Class). This is similar to Scala ◎ object DataProviderManager { fun registerDataProvider(provider: DataProvider) { // ... } val allDataProviders: Collection<DataProvider> get() = // ... } DataProviderManager.registerDataProvider(...)
  25. Give it a whirl Enough of the theory & syntax

    it’s time to do some coding.
  26. Useful Links ◎ Kotlin Reference Documents: https://kotlinlang.org/docs/reference/ ◎ Kotlin Koans:

    https://kotlinlang.org/docs/tutorials/koans.html ◎ Online Koans: http://try.kotlinlang.org/ ◎ These slides: https://speakerdeck.com/andybowes/hands-on-kotlin