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

Kotlin 101

Kotlin 101

In this talk, we will explore Kotlin programming language and the reason why it is important for the Java community.

Avatar for krupal shah

krupal shah

April 13, 2018
Tweet

More Decks by krupal shah

Other Decks in Programming

Transcript

  1. Original Goals of Java "Java is a blue collar language.

    It’s not PhD thesis material but a language for a job. Java feels very familiar to many different programmers because we preferred tried-and-tested things." - James Gosling in "The feel of Java", 1997 [https://pdfs.semanticscholar.org/5eb2/d00608ac08f4ca9f513066d8a81ea5358937.p df ]
  2. A decade of research A decade of research in programming

    languages [2000-2010] - Non-nullable type system - Pattern matching - Type Inference - Concurrency Mechanisms Functional programming mixed with OOP - Scala, Clojure, Go, D, Rust, Swift, Dart, Typescript
  3. Why Kotlin - Concise, safe, good tooling The only real

    advantage of Kotlin - Compiles to JVM, 100% interoperability with Java
  4. Properties Properties var - mutable val - immutable (aka final)

    Syntax: val a : Int = 10 val a = 10 //inferred int
  5. Getters and Setters var age : Int get() { return

    calculateAgeFromBirthDate() } set(value){ validate(age) } val can not have set.
  6. Null Safety var str : String = "xyz" //non nullable

    type str = null //error var a: String? //nullable type String and String? are not the same. val length = a?.length //calculate length only if a is not null
  7. Null Safety Elvis operator val length = a?.length ?: 5

    //if a is null, length will be 5 Not-null assertion Operator val length = a!!.length //if a is null, throw NPE
  8. Functions fun method() { //returns Unit } fun sum(x:Int, y:Int)

    : Int { return x + y; } //single line functions fun sum(x:Int, y:Int) = x + y; //optional parameters fun circumference(radius:Int = 1) = 2 * 3.14 * radius;
  9. Casting InstanceOf : is Casting : as if(activity is BaseActivity){

    (activity as BaseActivity).hideKeyboard() } Smart Cast if(activity is BaseActivity){ activity.hideKeyboard() }
  10. Control Flow Simple If: var a, b, max = 0;

    if(a > b){ max = a } else { max = b } Everything is an expression: val max = if (a > b) a else b
  11. Control Flow When expression (aka Switch with pattern matching) val

    a = 100; when(a) { is 0,5 -> print("0 or 5") in 20..50 -> print("20 to 50") is 10 -> print("10") else -> print("Invalid") }
  12. Control Flow For loops: val arr = [1,2,3] for (i

    in arr.indices) { println(array[i]) } for(i in arr){ print("array value $i") }
  13. Control Flow Ranges: for (i in 1..3) { println(i) }

    Index and value: for((index,value) in arr.withIndex()){ print("value $value is on index $index") }
  14. Classes and Interfaces Everything is explicit Classes and methods are

    final by default. Primary constructor is explicit. open class Base { open fun methodToOverride() {} fun finalMethod() {} } class Extended : Base() { override fun methodToOverride() {} } //implementing interfaces class Extended : Base(), Runnable { override fun run() {} }
  15. Classes and Interfaces //extending classes and implementing interfaces class Extended

    : Base(), Runnable { override fun run() {} } Multiple classes/interfaces can be defined in single file. Everything is an object. No primitives. There is no new operator: val obj = Extended() There is no static!
  16. Visibility Modifiers Public, private and internal Everything is public by

    default. There is no package private. internal is accessible inside the same module.
  17. Singletons Object Declarations: object Test { val a = 10

    } print("test ${Test.a}") Object Expressions: val callback = object : Consumer<String> { override fun accept(String value) {} } Handler().postDelayed(object : Runnable { override fun run() {}
  18. Extension Functions Date.format() : String { val formatter = SimpleDateFormat("dd

    MM yyyy") return formatter.format(this) } //calling extension function val now = Date() String strDate = now.format() Extension functions are resolved statically
  19. Higher Order functions fun registerItemClickListener(listener : (Item) -> Unit){} //calling

    adapter.registerItemClickListener{ user -> updateUser(user)} Higher order functions along with extension functions: //in extensions.kt fun Adapter.registerItemClickListener(listener : (Int, Item)-> Unit){ } //calling adapter.registerItemClickListener{ user -> updateUser(user)}
  20. Companion Objects Aka class objects class Example { companion object

    { const val a = 10 } } print("a = ${Example.a}")
  21. Common Misconceptions Kotlin is fast. Generated output by Kotlin is

    small. Kotlin is similar to Javascript or Typescript. Java libraries can not be used with Kotlin.