Slide 1

Slide 1 text

Hello, Kotlin A gentle introduction to Kotlin by Kshitij Chauhan Android Developer Kotlin Enthusiast @haroldadmin
 Github, Twitter

Slide 2

Slide 2 text

Kotlin • A programming language developed by JetBrains • Pragmatic, readable, elegant syntax • Cross compiles to Java Bytecode, Javascript, and Native Binaries • Used for Android, Backend and Websites

Slide 3

Slide 3 text

Why Kotlin? I mean, isn’t it just shorter Java?

Slide 4

Slide 4 text

Quite a few reasons why Statically typed Type inference Runs on the JVM Fully compatible with Java libraries Expressive Syntax Coroutines Mixed paradigm: Object oriented and Functional Excellent tooling Very readable Property delegates Immutable by default Null Safety Lambdas Data classes String interpolation Cross compiles to JavaScript Cross compiles to native binary code Top level functions and properties Great for DSLs Functions are first class citizens Open Source Extension Functions

Slide 5

Slide 5 text

Kotlin was the second most loved language on StackOverflow Developer Survey, 2018
 100,000 respondents That’s a lot of love ❤ Loved by Developers https://insights.stackoverflow.com/survey/2018#most-loved-dreaded-and-wanted

Slide 6

Slide 6 text

– James Lau, Product Manager, Google “Android developers are loving the language with over 97% satisfaction in our most recent survey.” https://android-developers.googleblog.com/2018/10/kotlin-momentum-for-android-and-beyond.html

Slide 7

Slide 7 text

Let’s get started with Kotlin! Disclaimer: 
 This presentation is aimed at beginners in programming. I’m going to be simplifying a lot of things. Code Samples available here
 https://github.com/haroldadmin/Hello-Kotlin

Slide 8

Slide 8 text

Basics first

Slide 9

Slide 9 text

Variables val greeting : String = "Hello, world!" Declares an immutable variable Variable name Variable type Variable value

Slide 10

Slide 10 text

Variables val and var var greeting : String = "Hello, world!" Declares a mutable variable Variable name Variable type Variable value

Slide 11

Slide 11 text

Variables val and var Variables declared with ‘val’ are immutable, which means once a value is assigned to them, it can not change. val greeting: String = "Hello, world!” greeting = "Goodbye, world!" // Error Variables declared with ‘var’ can be changed as many times as you want. var greeting : String = "Hello, world!" greeting = "Goodbye, world!" //

Slide 12

Slide 12 text

As a rule of thumb, always declare a variable with ‘val’. Use ‘var’ only when absolutely necessary. val = var = ☹

Slide 13

Slide 13 text

Kotlin is smart val greeting : String = "Hello, world!” val greeting = "Hello, world!" // // Compiler can figure out that this is a String You don’t have to specify the variable type explicitly, the compiler can figure it out for itself This is called Type Inference. If the variable type is obvious from its definition, the compiler will automatically figure it out too. This leads to less work on the programmer’s part, and makes the code more readable by removing unnecessary noise.

Slide 14

Slide 14 text

Functions fun returnHello(): String { return "Hello!" } ‘fun’ denotes a function Function name Return type

Slide 15

Slide 15 text

Functions fun returnHello(): String { return "Hello!" } Just like you specify the type of the variable after it’s name, you specify the function’s return after the function name. If the function code is trivial, the parenthesis may be omitted for brevity. Using this syntax, the above function can also be written as: fun returnHello() = "Hello"

Slide 16

Slide 16 text

Functions If the function code is trivial, the parenthesis may be omitted for brevity. Using this syntax, the last function can also be written as: fun returnHello(): String = "Hello" fun returnHello() = "Hello" Type inference works for functions too. We can further shorten the above function to:

Slide 17

Slide 17 text

Functions For functions that don’t return a value, we use a special return type called ‘Unit’. Kotlin does not have a ‘void’ keyword or type. fun greet(): Unit { println("Hello!") } If no return type is specified, then the compiler assumes it to be Unit. fun greet() { println("Hello!") }

Slide 18

Slide 18 text

Functions Functions can have input values. Each parameter should explicitly specify its type. fun myPrint(name: String): Unit { println(name) } Input parameter and its return type

Slide 19

Slide 19 text

Functions Input parameters are always passed by reference. You can not modify the value of input parameters. You can, however, modify any vars outside the function scope. var outerName = "Java" fun myPrint(name: String): Unit { name = "C++" // Error outerName = "Kotlin" // ( }

Slide 20

Slide 20 text

String formatting Because strings are hard

Slide 21

Slide 21 text

String formatting Formatting strings is annoying in almost every language. Kotlin however, has an elegant solution to this problem: String Interpolation fun myPrint(name: String) { println("My name is ${name}") } myPrint("Kotlin") // Output = "My name is Kotlin

Slide 22

Slide 22 text

String formatting fun myPrint(name: String) { println("My name is ${name}") } String interpolation allows you to put values into Strings using an elegant syntax, without having to concatenate things or printing things out in multiple steps.

Slide 23

Slide 23 text

Arrays Fixed size collections

Slide 24

Slide 24 text

Arrays val fourEvenNumbers: Array = arrayOf(0, 2, 4, 6) Type of the variable = Array of Integers Standard Library function to build Arrays Or, simply: val fourEvenNumbers = arrayOf(0, 2, 4, 6) // Type Inference is awesome

Slide 25

Slide 25 text

Arrays Also just like most languages, Arrays are fixed in size. Once initialised, elements can’t be added or removed. Use Lists for dynamically sized collections. val fourOddNumbers: Array = arrayOf(0, 1, 3, 5) fourOddNumbers.add(9) // Error fourOddNumbers.remove(0) // Error Elements in an array can be accessed using their Index. Kotlin has zero based indexing, just like normal programming languages. val fourOddNumbers: Array = arrayOf(0, 1, 3, 5) println(fourOddNumbers[0])

Slide 26

Slide 26 text

Lists Dynamically sized collections

Slide 27

Slide 27 text

Lists val fourEvenNumbers: List = listOf(0, 2, 4, 6) Type of the variable = List of Integers Standard Library function to build lists Or, if you want a list that can be mutated: val fourEvenNumbers: MutableList = mutableListOf(0, 2, 4, 6) Mutable List of Integers

Slide 28

Slide 28 text

With those basics out of the way, It’s time to say Hello!

Slide 29

Slide 29 text

Hello world! Kotlin style

Slide 30

Slide 30 text

Simple Hello fun main(): Unit { println("Hello, world!") }

Slide 31

Slide 31 text

Personalised Hello // Wrong ❌ fun main(name: String): Unit { println("Hello, ${name}!") }

Slide 32

Slide 32 text

The main function has a very specific syntax. It can be one of the following two types: Or, if you need input parameters: fun main() { // Your Code } fun main(args: Array) { // Your Code }

Slide 33

Slide 33 text

Personalised Hello // Correct ✅ fun main(args: Array) { val name = args[0] println(name) }

Slide 34

Slide 34 text

Classes

Slide 35

Slide 35 text

Classes Classes are a way to wrap Data and Methods into one entity. This is useful for modelling real world things class Person() { // Contents of your class } Data = Variables inside the class
 Methods = Functions inside the class

Slide 36

Slide 36 text

Properties The variables inside the class are called Properties of the class. They are declared in the constructor, just after the name of the class class Person(val name: Int, val age: Int) { // Contents of the class } A new instance of this class can be created by supplying the values of all the properties in the constructor. The ‘new’ keyword is not required in Kotlin val kshitij = Person("Kshitij", 21)

Slide 37

Slide 37 text

Methods The functions declared in a class are called Methods of that class. class Person(val name: Int, val age: Int) { fun greet() { println("Hello, $name") } } These functions can be accessed through objects of this class. val kshitij = Person("Kshitij", 21) kshitij.greet()

Slide 38

Slide 38 text

Inheritance

Slide 39

Slide 39 text

Inheritance Java, Kotlin, and most other JVM languages only support Single Inheritance. In Kotlin, classes are final by default, which means no other class can inherit from them. To make a class inheritable, you have declare it with the ‘open’ keyword. open class Animal(val numberOfLimbs: Int) class Dog(): Animal(numberOfLimbs = 4)

Slide 40

Slide 40 text

Abstract Classes An Abstract class is a type of class that does not implement some of its functionality: Whether it be functions, or properties. Abstract classes are used when it makes sense to share some trait between a lot of classes, but that common trait is slightly different for each one. abstract class Animal(val numberOfLimbs: Int) { abstract fun interact() }

Slide 41

Slide 41 text

Abstract Classes The ‘interact’ trait is common to all Animals, but each Animal does it slightly differently. Therefore, it makes sense to use an Abstract class with an unimplemented ‘interact’ function here. All subclasses of Animal will have their own implementation. abstract class Animal(val numberOfLimbs: Int) { abstract fun interact() } class Cat(): Animal(numberOfLimbs = 4) { override fun interact() { println("Meow!") } } class Dog(): Animal(numberOfLimbs = 4) { override fun interact() { println("Woof woof!") } }

Slide 42

Slide 42 text

Interfaces

Slide 43

Slide 43 text

Interfaces Interfaces are a construct which have only unimplemented details. They are used to provide a common contract different implementations of an interface. While a class can only inherit from only one super class, it can implement any number of interfaces. Therefore, interfaces are a much better method of achieving Polymorphism. interface MobilePhone { fun call() fun text() }

Slide 44

Slide 44 text

Lambdas

Slide 45

Slide 45 text

Lambdas • Lambdas are nameless functions • They can be passed as parameters to other functions • They have a set of Inputs and a Single output, just like regular functions. • Great for scenarios where you have to pass an action, instead of a value to some other object. • Lambdas are really, like really, freakin’ cool ,

Slide 46

Slide 46 text

Why would I want to use them, though? I’m not really sold on the whole “Lambdas are cool” thing yet, you know?

Slide 47

Slide 47 text

Question Time You’re given a list of numbers. Filter it and give me back the even numbers.

Slide 48

Slide 48 text

fun filterEvenNumbers(list: List): List { val listOfEvenNumbers = mutableListOf() for (i in list) { if (i % 2 == 0) { listOfEvenNumbers.add(i) } } return listOfEvenNumbers } Traditional approach

Slide 49

Slide 49 text

BOOOOOOOOO . We’re still talking about Lambdas, trust me

Slide 50

Slide 50 text

The Lambda Approach val listOfEvenNumbers = list.filter({ number -> number % 2 == 0 }) That’s a lambda!

Slide 51

Slide 51 text

Lambdas are really just a block of code • They have a one or more inputs. In this case, the input is just one number. • The inputs are separated from the body of the lambda with an arrow: ‘->’ • The body of the lambda is executed, and the value of the last expression becomes the return value of the lambda. In this case, the last expression is: number % 2 == 0 • This expression evaluates to a boolean, and therefore the lambda’s return value is a Boolean. { number -> number % 2 == 0 }

Slide 52

Slide 52 text

• ‘filter’ is a function in the standard library, whose definition takes in a lambda as a parameter.
 • The lambda takes in an integer, and returns a boolean value. How that boolean value is calculated depends on the body of the lambda function. • This flexibility of deciding the value of the lambda makes the filter function very powerful. We can easily change the condition in the lambda to return a completely different result from the filter function. list.filter({ number -> number % 2 == 0 }) fun filter(predicate: (Int) -> Boolean): List

Slide 53

Slide 53 text

– Me, 2019 “But that’s not all”

Slide 54

Slide 54 text

Last Parameter Syntax list.filter({ i -> i % 2 == 0 }) list.filter { i -> i % 2 == 0 } If a function takes in a lambda as its last input parameter, the lambda can be written outside the parenthesis of input arguments. While this may not seem like a big deal in this case, it increases code readability exponentially in more complex functions.

Slide 55

Slide 55 text

Further simplification list.filter({ i -> i % 2 == 0 }) list.filter { it % 2 == 0 } If the lambda has only one input parameter, such as in the above case, you don’t need to explicitly name the parameter. You can refer to it using the keyword ‘it’

Slide 56

Slide 56 text

fun filterEvens(): List = list.filter { it % 2 == 0 } Lambdas = Readability++ fun filterEvenNumbers(list: List): List { val listOfEvenNumbers = mutableListOf() for (i in list) { if (i % 2 == 0) { listOfEvenNumbers.add(i) } } return listOfEvenNumbers } vs

Slide 57

Slide 57 text

No content

Slide 58

Slide 58 text

This is what makes Kotlin so great. It focuses on making the life of the programmer easier. It doesn’t force you to write unnecessary noise. It wants you to simply focus on solving your problem.

Slide 59

Slide 59 text

There’s a lot more Coroutines Property delegates Null Safety Data classes Extension Functions Infix Functions Tail Recursive calls Even More Syntactic Sugar Interoperability with Java Generics Init Blocks Input/Output And a lot more things. Follow me on Twitter and Github to stay up to date! Find my Kotlin Android apps and other projects on GitHub/Gitlab. @haroldadmin

Slide 60

Slide 60 text

I hope you go on to explore Kotlin more. It is a beautiful, pragmatic, and elegant language. It makes writing code a pleasure. Language website
 https://www.kotlinlang.org
 Link to these slides
 https://speakerdeck.com/haroldadmin/hello-kotlin
 Link to code samples
 https://github.com/haroldadmin/Hello-Kotlin
 Kotlin bootcamp by Google
 https://in.udacity.com/course/kotlin-bootcamp-for-programmers--ud9011
 Join the slack channel
 http://slack.kotlinlang.org/

Slide 61

Slide 61 text

Questions 
 Comments and memes
 Are Very Welcome Kshitij Chauhan Android Developer Kotlin Enthusiast @haroldadmin
 Github, Twitter