Share
Embed
Hello, Kotlin
A gentle introduction to Kotlin for those who are Programming Beginners.
Kshitij Chauhan
April 11, 2019
Transcript
61 slides
-
Hello, Kotlin A gentle introduction to Kotlin by Kshitij Chauhan
Android Developer Kotlin Enthusiast @haroldadmin Github, Twitter -
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 -
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 -
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 -
– 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 -
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 -
Variables val greeting : String = "Hello, world!" Declares an
immutable variable Variable name Variable type Variable value -
Variables val and var var greeting : String = "Hello,
world!" Declares a mutable variable Variable name Variable type Variable value -
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!" // -
As a rule of thumb, always declare a variable with
‘val’. Use ‘var’ only when absolutely necessary. val = var = ☹ -
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. -
Functions fun returnHello(): String { return "Hello!" } ‘fun’ denotes
a function Function name Return type -
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" -
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: -
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!") } -
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 -
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" // ( } -
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 -
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. -
Arrays val fourEvenNumbers: Array<Int> = 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 -
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<Int> = 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<Int> = arrayOf(0, 1, 3, 5) println(fourOddNumbers[0]) -
Lists val fourEvenNumbers: List<Int> = 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<Int> = mutableListOf(0, 2, 4, 6) Mutable List of Integers -
Personalised Hello // Wrong ❌ fun main(name: String): Unit {
println("Hello, ${name}!") } -
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<String>) { // Your Code } -
Personalised Hello // Correct ✅ fun main(args: Array<String>) { val
name = args[0] println(name) } -
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 -
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) -
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() -
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) -
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() } -
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!") } } -
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() } -
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 , -
Why would I want to use them, though? I’m not
really sold on the whole “Lambdas are cool” thing yet, you know? -
Question Time You’re given a list of numbers. Filter it
and give me back the even numbers. -
fun filterEvenNumbers(list: List<Int>): List<Int> { val listOfEvenNumbers = mutableListOf<Int>() for
(i in list) { if (i % 2 == 0) { listOfEvenNumbers.add(i) } } return listOfEvenNumbers } Traditional approach -
The Lambda Approach val listOfEvenNumbers = list.filter({ number -> number
% 2 == 0 }) That’s a lambda! -
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 } -
• ‘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<Int> -
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. -
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’ -
fun filterEvens(): List<Int> = list.filter { it % 2 ==
0 } Lambdas = Readability++ fun filterEvenNumbers(list: List<Int>): List<Int> { val listOfEvenNumbers = mutableListOf<Int>() for (i in list) { if (i % 2 == 0) { listOfEvenNumbers.add(i) } } return listOfEvenNumbers } vs -
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. -
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 -
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/ -
Questions Comments and memes Are Very Welcome Kshitij Chauhan
Android Developer Kotlin Enthusiast @haroldadmin Github, Twitter