SlideShare a Scribd company logo
1 of 64
Introduction to Kotlin
for android developers
About me
Mohamed Wael
Senior Android developer @ Vodafone shared services Egypt.
Computer Science 2015, Mansoura University.
MohamedWael iMohamedWael MohamedWael
Online Tools
•Try Kotlin in your browser
•Full Kotlin Reference
•A list of Kotlin resources
What is Kotlin
•Kotlin is a cross-platform, statically typed, general-
purpose programming language with type inference.
•Developed by JetBrains, the creator of the android
studio.
•In October 2017, Kotlin is officially supported by Google
for Android.
What is Kotlin
•Kotlin mainly targets the JVM, but also compiles to
JavaScript or native code.
•Kotlin is Open Source and it costs nothing to adopt.
•Kotlin can be learned easily. It can be learned easily by
simply reading the language reference.
•The syntax is clean and intuitive(easy to use and
understand).
•Type inference allows its syntax to be more concise.
Statically typed languages
•A language is statically typed if the type of a variable is
known at compile time.
•The main advantage here is that all kinds of checking
can be done by the compiler, and therefore a lot of
trivial bugs are caught at a very early stage.
•Examples: C, C++, Java, Rust, Go, Scala
Statically typed languages
/* Java Code */
static int num1, num2; //explicit declaration
num1 = 20; //use the variables anywhere
num2 = 30;
/* Kotlin Code*/
val a: Int
val b: Int
a = 5
b = 10
Benefits of Kotlin Language
•Kotlin compiles to JVM bytecode or JavaScript:
• Like Java, Bytecode is the compiled format for Kotlin
programs also.
• Bytecode means Programming code that, once
compiled, is run through a virtual machine instead of
the computer’s processor.
Benefits of Kotlin Language
•Kotlin compiles to JVM bytecode or JavaScript:
• By using this approach, source code can be run on any
platform once it has been compiled and run through
the virtual machine.
• Once a kotlin program has been converted to
bytecode, it can be transferred across a network and
executed by JVM(Java Virtual Machine).
Benefits of Kotlin Language
•Kotlin programs can use all existing Java Frameworks and
Libraries:
• Kotlin programs can use all existing java frameworks
and libraries, even advanced frameworks that rely on
annotation processing.
• The main important thing about kotlin language is that
it can easily integrate with Maven, Gradle and other
build systems.
Benefits of Kotlin Language
•Kotlin’s null-safety is great
•Now get rid of
NullPointerException. This type of
system helps us to avoid null
pointer exceptions.
Benefits of Kotlin Language
•Kotlin’s null-safety is great
•In Kotlin the system simply refuses to compile code that
tries to assign or return null. Consider the following
example:
val name: String = null // tries to assign null, won’t compile.
fun getName(): String = null // tries to return null, won’t compile.
Benefits of Kotlin Language
•But, what if we need nullability
• In some special cases if we need nullability in our
program then we have to ask Kotlin very nicely.
• Every Nullable type require some special care and
treatment. We can’t treat them the same way as non-
nullable types and this is a very good thing.
Benefits of Kotlin Language
•But, what if we need nullability
• We have to add “?” after the variable type. Kotlin also
fails at compile-time whenever a NullPointerException
may be thrown at run-time. Consider the following
example
val name: String? = null //assigned null and it will compile also.
fun getName(): String? = null //returned null and it will compile too.
Benefits of Kotlin Language
•But, what if we need nullability
/* won’t compile */
val name: String? = null
val len = name.length
/* correct way */
val name: String? = null
val len = name?.length
Kotlin file extention
•Filename extensions of the Java are .java, .class, .jar but
on the other hand filename extensions of the Kotlin are
.kt and .kts.
The entry point to a Kotlin
•Like in Java, C and C++, the entry point to a Kotlin
program is a function named “main”. Basically, it passed
an array containing any command line arguments.
•Consider the following example:
//package level function, which return Unit
//and takes an array of string as parameter
fun main(args: Array<String>) {
val scope = "world"
println("Hello, $scope!") //semicolons are optional
}
Comments and package
// Single-line comments start with //
/*
Multi-line comments look like this.
*/
// The "package" keyword works in the same way as in Java.
package com.example.kotlin
Declaring values and variables
•Declaring values is done using either "var" or "val".
•"val" declarations cannot be reassigned, whereas "vars"
can.Consider the following example:
val fooVal = 10 // we cannot later reassign fooVal to something else
var fooVar = 10
fooVar = 20 // fooVar can be reassigned
Type inference
•In most cases, Kotlin can determine what the type of a
variable is, so we don't have to explicitly specify it every
time. We can explicitly declare the type of a variable like
so:
•Strings can be represented in a similar way as in Java.
Escaping is done with a backslash.
val foo: Int = 7
val fooString = "My String Is Here!"
val barString = "Printing on a new line?nNo Problem!"
val bazString = "Do you want to add a tab?tNo Problem!"
println(fooString)
println(barString)
println(bazString)
String representation
•Strings can be represented in a similar way as in Java.
Escaping is done with a backslash.
val fooString = "My String Is Here!"
val barString = "Printing on a new line?nNo Problem!"
val bazString = "Do you want to add a tab?tNo Problem!"
println(fooString)
println(barString)
println(bazString)
String template expression
•Strings can contain template expressions.
•A template expression starts with a dollar sign ($).
val fooTemplateString = "$fooString has ${fooString.length} characters"
println(fooTemplateString) // => My String Is Here! has 18 characters
Raw string
•A raw string is delimited by a triple quote (""").
•Raw strings can contain newlines and any other
characters.
val fooRawString = """
fun helloWorld(val name : String) {
println("Hello, world!")
}
"""
println(fooRawString)
Nullable Type
•For a variable to hold null it must be explicitly specified
as nullable.
•A variable can be specified as nullable by appending a ?
to its type.
•We can access a nullable variable by using the ?.
operator.
•We can use the ?: operator to specify an alternative
value to use if a variable is null.
Nullable Type
var fooNullable: String? = "abc"
println(fooNullable?.length) // => 3
println(fooNullable?.length ?: -1) // => 3
fooNullable = null
println(fooNullable?.length) // => null
println(fooNullable?.length ?: -1) // => -1
Functions declaration
•Functions can be declared using the "fun" keyword.
•Function arguments are specified in brackets after the
function name.
•Function arguments can optionally have a default value.
•The function return type, if required, is specified after
the arguments. fun hello(name: String = "world"): String {
return "Hello, $name!"
}
println(hello("foo")) // => Hello, foo!
println(hello(name = "bar")) // => Hello, bar!
println(hello()) // => Hello, world!
"vararg" keyword
•A function parameter may be marked with the "vararg"
keyword to allow a variable number of arguments to be
passed to the function.
fun varargExample(vararg names: Int) {
println("Argument has ${names.size} elements")
}
varargExample() // => Argument has 0 elements
varargExample(1) // => Argument has 1 elements
varargExample(1, 2, 3) // => Argument has 3 elements
Single expression function
•When a function consists of a single expression then
the curly brackets can be omitted. The body is specified
after a = symbol.
•If the return type can be inferred then we don't need to
specify it.
fun odd(x: Int): Boolean = x % 2 == 1
println(odd(6)) // => false
println(odd(7)) // => true
fun even(x: Int) = x % 2 == 0
println(even(6)) // => true
println(even(7)) // => false
Function return type inference
•If the return type can be inferred then we don't need to
specify it.
fun even(x: Int) = x % 2 == 0
println(even(6)) // => true
println(even(7)) // => false
First-class citizen
•In Kotlin, functions are first-class citizen.
•It means that functions can be assigned to the
variables, passed as an arguments or returned from
another function.
•While Kotlin is statically typed, to make it possible,
functions need to have a type. It exists and it is called
function type.
Function Type
• The function type that returns nothing useful
(Unit) and takes no arguments.
• The function type that returns Int and takes
single argument of type Int.
• The function type that returns another
function that returns nothing useful (Unit). Both
functions take no arguments.
()->Unit
(Int)->Int
()->()->Unit
Function Type
•Function type is just a syntactic sugar for an interface,
but the interface cannot be used explicitly. Nevertheless
we can use function types like interfaces, what includes
using them as type arguments or implementing them:
class MyFunction : () -> Unit {
override fun invoke() {
println("I am called")
}
}
fun main(args: Array<String>) {
val function = MyFunction()
function() // Prints: I am called
}
Function Type
•We can also use them to type local variables, properties
or arguments:
val greet: () -> Unit
val square: (Int) -> Int
val producePrinter: () -> () -> Unit
Function Type
•Functions can take functions as arguments and return
functions.
•Named functions can be specified as arguments using
the :: operator.
fun not(f: (Int) -> Boolean): (Int) -> Boolean {
return { n -> !f.invoke(n) }
}
val notOdd = not(::odd)
val notEven = not(::even)
The "class" keyword
•The "class" keyword is used to declare classes.
•To create a new instance we call the constructor.
•Note that Kotlin does not have a "new" keyword.
class ExampleClass(val x: Int) {
fun memberFunction(y: Int): Int {
return x + y
}
infix fun infixMemberFunction(y: Int): Int {
return x * y
}
}
Instantiating an object
•To create a new instance we call the constructor.
•Data classes are a concise way to create classes that just
hold data.
•The "hashCode"/"equals" and "toString" methods are
automatically
generated.
val fooExampleClass = ExampleClass(7)
// Member functions can be called using dot notation.
println(fooExampleClass.memberFunction(4)) // => 11
data class DataClassExample(val x: Int, val y: Int, val z: Int)
val fooData = DataClassExample(1, 2, 4)
println(fooData) // => DataClassExample(x=1, y=2, z=4)
Instantiating an object
// Objects can be destructured into multiple variables.
val (a, b, c) = fooCopy
println("$a $b $c") // => 1 100 4
// destructuring in "for" loop
for ((a, b, c) in listOf(fooData)) {
println("$a $b $c") // => 1 100 4
}
val mapData = mapOf("a" to 1, "b" to 2)
// Map.Entry is destructurable as well
for ((key, value) in mapData) {
println("$key -> $value")
}
Kotlin functions
•The "with" function is similar to the JavaScript "with"
statement.
data class MutableDataClassExample(var x: Int, var y: Int, var z: Int)
val fooMutableData = MutableDataClassExample(7, 4, 9)
with (fooMutableData) {
x -= 2
y += 2
z--
}
println(fooMutableData) // => MutableDataClassExample(x=5, y=6, z=8)
The "listOf" function.
/*
We can create a list using the "listOf" function.
The list will be immutable - elements cannot be added or removed.
*/
val fooList = listOf("a", "b", "c")
println(fooList.size) // => 3
println(fooList.first()) // => a
println(fooList.last()) // => c
// Elements of a list can be accessed by their index.
println(fooList[1]) // => b
Kotlin functions
// A mutable list can be created using the "mutableListOf" function.
val fooMutableList = mutableListOf("a", "b", "c")
fooMutableList.add("d")
println(fooMutableList.last()) // => d
println(fooMutableList.size) // => 4
// We can create a set using the "setOf" function.
val fooSet = setOf("a", "b", "c")
println(fooSet.contains("a")) // => true
println(fooSet.contains("z")) // => false
// We can create a map using the "mapOf" function.
val fooMap = mapOf("a" to 8, "b" to 7, "c" to 9)
// Map values can be accessed by their key.
println(fooMap["a"]) // => 8
Kotlin functions
•An example of using a sequence to generate Fibonacci
numbers, as below:
/*
Sequences represent lazily-evaluated collections.
We can create a sequence using the "generateSequence" function.
*/
val fooSequence = generateSequence(1, { it + 1 })
val x = fooSequence.take(10).toList()
println(x) // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Kotlin functions
fun fibonacciSequence(): Sequence<Long> {
var a = 0L
var b = 1L
fun next(): Long {
val result = a + b
a = b
b = result
return a
}
return generateSequence(::next)
}
val y = fibonacciSequence().take(10).toList()
println(y) // => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Kotlin functions
•A higher order function is a function that accepts or
return another function.
•A "for" loop can be used with
anything that provides an iterator.
// Kotlin provides higher-order functions for working with collections.
val z = (1..9).map { it * 3 }
.filter { it < 20 }
.groupBy { it % 2 == 0 }
.mapKeys { if (it.key) "even" else "odd" }
println(z) // => {odd=[3, 9, 15], even=[6, 12, 18]}
for (c in "hello") {
println(c)
}
Kotlin loops
•A "for" loop can be used with anything that provides an
iterator.
•"while" loops work in the same way as
other languages.
for (c in "hello") {
println(c)
}
var ctr = 0
while (ctr < 5) {
println(ctr)
ctr++
}
//do-while
do {
println(ctr)
ctr++
} while (ctr < 10)
"if" expression
•"if" can be used as an expression that returns a value.
•For this reason the ternary ?: operator is not needed in
Kotlin. val num = 5
val message = if (num % 2 == 0) "even" else "odd"
println("$num is $message") // => 5 is odd
" when" expression
•"when" can be used as an alternative to "if-else if"
chains.
val i = 10
when {
i < 7 -> println("first block")
fooString.startsWith("hello") -> println("second block")
else -> println("else block")
}
" when" expression
// "when" can be used with an argument.
when (i) {
0, 21 -> println("0 or 21")
in 1..20 -> println("in the range 1 to 20")
else -> println("none of the above")
}
// "when" can be used as a function that returns a value.
var result = when (i) {
0, 21 -> "0 or 21"
in 1..20 -> "in the range 1 to 20"
else -> "none of the above"
}
println(result)
The "is" operator
•We can check if an object is of a particular type by using
the "is" operator.
•If an object passes a type check then it can be used as
that type without explicitly casting it.
The "is" operator
fun smartCastExample(x: Any): Boolean {
if (x is Boolean) {
// x is automatically cast to Boolean
return x
} else if (x is Int) {
// x is automatically cast to Int
return x > 0
} else if (x is String) {
// x is automatically cast to String
return x.isNotEmpty()
} else {
return false
}
}
println(smartCastExample("Hello, world!")) // => true
println(smartCastExample("")) // => false
println(smartCastExample(5)) // => true
println(smartCastExample(0)) // => false
println(smartCastExample(true)) // => true
The "is" operator
•Smartcast also works with when block
// Smartcast also works with when block
fun smartCastWhenExample(x: Any) = when (x) {
is Boolean -> x
is Int -> x > 0
is String -> x.isNotEmpty()
else -> false
}
Extensions function
•Extensions are a way to add new functionality to a class.
•This is similar to C# extension methods.
fun String.remove(c: Char): String {
return this.filter { it != c }
}
println("Hello, world!".remove('l')) // => Heo, word!
Enum classes
// Enum classes are similar to Java enum types.
enum class EnumExample {
A, B, C
}
fun printEnum() = println(EnumExample.A) // => A
The "object" keyword
•The "object" keyword can be used to create singleton
objects.
•We cannot instantiate it but we can refer to its unique
instance by its name.
•This is similar to Scala singleton objects.
The "object" keyword
object ObjectExample {
fun hello(): String {
return "hello"
}
override fun toString(): String {
return "Hello, it's me, ${ObjectExample::class.simpleName}"
}
}
fun useSingletonObject() {
println(ObjectExample.hello()) // => hello
// In Kotlin, "Any" is the root of the class hierarchy,
// just like "Object" is in Java
val someRef: Any = ObjectExample
println(someRef) // => Hello, it's me, ObjectExample
}
The "object" keyword
•The not-null assertion operator (!!) converts any value
to a non-null type and throws an exception if the value
is null.
var b: String? = "abc"
val l = b!!.length
Overloading operators
•You can also overload operators through an extension
methods.
Overloadingoperators
data class Counter(var value: Int) {
// overload Counter += Int
operator fun plusAssign(increment: Int) {
this.value += increment
}
// overload Counter++ and ++Counter
operator fun inc() = Counter(value + 1)
// overload Counter + Counter
operator fun plus(other: Counter) = Counter(this.value + other.value)
// overload Counter * Counter
operator fun times(other: Counter) = Counter(this.value * other.value)
// overload Counter * Int
operator fun times(value: Int) = Counter(this.value * value)
// overload Counter in Counter
operator fun contains(other: Counter) = other.value == this.value
// overload Counter[Int] = Int
operator fun set(index: Int, value: Int) {
this.value = index + value
}
// overload Counter instance invocation
operator fun invoke() = println("The value of the counter is $value")
}
Overloading operators
// overload -Counter
operator fun Counter.unaryMinus() = Counter(-this.value)
fun operatorOverloadingDemo() {
var counter1 = Counter(0)
var counter2 = Counter(5)
counter1 += 7
println(counter1) // => Counter(value=7)
println(counter1 + counter2) // => Counter(value=12)
println(counter1 * counter2) // => Counter(value=35)
println(counter2 * 2) // => Counter(value=10)
println(counter1 in Counter(5)) // => false
println(counter1 in Counter(7)) // => true
counter1[26] = 10
println(counter1) // => Counter(value=36)
counter1() // => The value of the counter is 36
println(-counter2) // => Counter(value=-5)
}
Resources
• https://kotlinlang.org/docs/reference/
• https://en.wikipedia.org/wiki/Kotlin_(programming_language)
• https://stackoverflow.com/questions/1517582/what-is-the-difference-between-
statically-typed-and-dynamically-typed-languages
• https://www.xenonstack.com/blog/overview-kotlin-comparison-kotlin-java/
• https://blog.kotlin-academy.com/kotlin-programmer-dictionary-function-type-vs-
function-literal-vs-lambda-expression-vs-anonymous-edc97e8873e
• https://blog.kotlin-academy.com/kotlin-programmer-dictionary-2cb67fff1fe2
• https://medium.com/tompee/idiomatic-kotlin-higher-order-functions-and-function-
types-adb59172796
Introduction to Kotlin for Android developers
Introduction to Kotlin for Android developers

More Related Content

What's hot

Kotlin InDepth Tutorial for beginners 2022
Kotlin InDepth Tutorial for beginners 2022Kotlin InDepth Tutorial for beginners 2022
Kotlin InDepth Tutorial for beginners 2022Simplilearn
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Languageintelliyole
 
Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I Atif AbbAsi
 
Kotlin vs Java | Edureka
Kotlin vs Java | EdurekaKotlin vs Java | Edureka
Kotlin vs Java | EdurekaEdureka!
 
What is flutter and why should i care?
What is flutter and why should i care?What is flutter and why should i care?
What is flutter and why should i care?Sergi Martínez
 
Flutter presentation.pptx
Flutter presentation.pptxFlutter presentation.pptx
Flutter presentation.pptxFalgunSorathiya
 
Introduction to Android and Android Studio
Introduction to Android and Android StudioIntroduction to Android and Android Studio
Introduction to Android and Android StudioSuyash Srijan
 
Google flutter the easy and practical way
Google flutter the easy and practical wayGoogle flutter the easy and practical way
Google flutter the easy and practical wayAhmed Abu Eldahab
 
Introduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platformIntroduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platformEastBanc Tachnologies
 
The Full Stack Web Development
The Full Stack Web DevelopmentThe Full Stack Web Development
The Full Stack Web DevelopmentSam Dias
 
Flutter Tutorial For Beginners | Edureka
Flutter Tutorial For Beginners | EdurekaFlutter Tutorial For Beginners | Edureka
Flutter Tutorial For Beginners | EdurekaEdureka!
 
Introduction to flutter(1)
 Introduction to flutter(1) Introduction to flutter(1)
Introduction to flutter(1)latifah alghanem
 
Build beautiful native apps in record time with flutter
Build beautiful native apps in record time with flutterBuild beautiful native apps in record time with flutter
Build beautiful native apps in record time with flutterRobertLe30
 

What's hot (20)

Kotlin InDepth Tutorial for beginners 2022
Kotlin InDepth Tutorial for beginners 2022Kotlin InDepth Tutorial for beginners 2022
Kotlin InDepth Tutorial for beginners 2022
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Language
 
Intro to kotlin
Intro to kotlinIntro to kotlin
Intro to kotlin
 
Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I
 
Kotlin vs Java | Edureka
Kotlin vs Java | EdurekaKotlin vs Java | Edureka
Kotlin vs Java | Edureka
 
Flutter
FlutterFlutter
Flutter
 
What is flutter and why should i care?
What is flutter and why should i care?What is flutter and why should i care?
What is flutter and why should i care?
 
Flutter presentation.pptx
Flutter presentation.pptxFlutter presentation.pptx
Flutter presentation.pptx
 
Mobile Application Testing
Mobile Application TestingMobile Application Testing
Mobile Application Testing
 
Flutter workshop
Flutter workshopFlutter workshop
Flutter workshop
 
Introduction to Android and Android Studio
Introduction to Android and Android StudioIntroduction to Android and Android Studio
Introduction to Android and Android Studio
 
Rest assured
Rest assuredRest assured
Rest assured
 
Android studio ppt
Android studio pptAndroid studio ppt
Android studio ppt
 
Google flutter the easy and practical way
Google flutter the easy and practical wayGoogle flutter the easy and practical way
Google flutter the easy and practical way
 
Introduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platformIntroduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platform
 
Android studio
Android studioAndroid studio
Android studio
 
The Full Stack Web Development
The Full Stack Web DevelopmentThe Full Stack Web Development
The Full Stack Web Development
 
Flutter Tutorial For Beginners | Edureka
Flutter Tutorial For Beginners | EdurekaFlutter Tutorial For Beginners | Edureka
Flutter Tutorial For Beginners | Edureka
 
Introduction to flutter(1)
 Introduction to flutter(1) Introduction to flutter(1)
Introduction to flutter(1)
 
Build beautiful native apps in record time with flutter
Build beautiful native apps in record time with flutterBuild beautiful native apps in record time with flutter
Build beautiful native apps in record time with flutter
 

Similar to Introduction to Kotlin for Android developers

Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Mohamed Nabil, MSc.
 
Developer’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageDeveloper’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageAzilen Technologies Pvt. Ltd.
 
Kotlin for Android devs
Kotlin for Android devsKotlin for Android devs
Kotlin for Android devsAdit Lal
 
Kotlin what_you_need_to_know-converted event 4 with nigerians
Kotlin  what_you_need_to_know-converted event 4 with nigeriansKotlin  what_you_need_to_know-converted event 4 with nigerians
Kotlin what_you_need_to_know-converted event 4 with nigeriansjunaidhasan17
 
9054799 dzone-refcard267-kotlin
9054799 dzone-refcard267-kotlin9054799 dzone-refcard267-kotlin
9054799 dzone-refcard267-kotlinZoran Stanimirovic
 
Kotlin- Basic to Advance
Kotlin- Basic to Advance Kotlin- Basic to Advance
Kotlin- Basic to Advance Coder Tech
 
Android Application Development (1).pptx
Android Application Development (1).pptxAndroid Application Development (1).pptx
Android Application Development (1).pptxadityakale2110
 
Basics of kotlin ASJ
Basics of kotlin ASJBasics of kotlin ASJ
Basics of kotlin ASJDSCBVRITH
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard LibrarySantosh Rajan
 
Exploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentExploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentJayaprakash R
 
Intro to Kotlin
Intro to KotlinIntro to Kotlin
Intro to KotlinMagda Miu
 
Боремся с NPE вместе с Kotlin, Павел Шацких СберТех
Боремся с NPE вместе с Kotlin, Павел Шацких СберТехБоремся с NPE вместе с Kotlin, Павел Шацких СберТех
Боремся с NPE вместе с Kotlin, Павел Шацких СберТехСбертех | SberTech
 
Kotlin: A pragmatic language by JetBrains
Kotlin: A pragmatic language by JetBrainsKotlin: A pragmatic language by JetBrains
Kotlin: A pragmatic language by JetBrainsJigar Gosar
 

Similar to Introduction to Kotlin for Android developers (20)

Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Kotlin for Android Developers - 3
Kotlin for Android Developers - 3
 
Developer’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageDeveloper’s viewpoint on swift programming language
Developer’s viewpoint on swift programming language
 
Kotlin for Android devs
Kotlin for Android devsKotlin for Android devs
Kotlin for Android devs
 
Swift, swiftly
Swift, swiftlySwift, swiftly
Swift, swiftly
 
Should i Go there
Should i Go thereShould i Go there
Should i Go there
 
Kotlin what_you_need_to_know-converted event 4 with nigerians
Kotlin  what_you_need_to_know-converted event 4 with nigeriansKotlin  what_you_need_to_know-converted event 4 with nigerians
Kotlin what_you_need_to_know-converted event 4 with nigerians
 
#_ varible function
#_ varible function #_ varible function
#_ varible function
 
kotlin-nutshell.pptx
kotlin-nutshell.pptxkotlin-nutshell.pptx
kotlin-nutshell.pptx
 
9054799 dzone-refcard267-kotlin
9054799 dzone-refcard267-kotlin9054799 dzone-refcard267-kotlin
9054799 dzone-refcard267-kotlin
 
Kotlin- Basic to Advance
Kotlin- Basic to Advance Kotlin- Basic to Advance
Kotlin- Basic to Advance
 
Android Application Development (1).pptx
Android Application Development (1).pptxAndroid Application Development (1).pptx
Android Application Development (1).pptx
 
Basics of kotlin ASJ
Basics of kotlin ASJBasics of kotlin ASJ
Basics of kotlin ASJ
 
Hello to Kotlin
Hello to KotlinHello to Kotlin
Hello to Kotlin
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
 
Kotlin Basic & Android Programming
Kotlin Basic & Android ProgrammingKotlin Basic & Android Programming
Kotlin Basic & Android Programming
 
Exploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentExploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App development
 
Intro to Kotlin
Intro to KotlinIntro to Kotlin
Intro to Kotlin
 
Боремся с NPE вместе с Kotlin, Павел Шацких СберТех
Боремся с NPE вместе с Kotlin, Павел Шацких СберТехБоремся с NPE вместе с Kotlin, Павел Шацких СберТех
Боремся с NPE вместе с Kotlin, Павел Шацких СберТех
 
Kotlin: A pragmatic language by JetBrains
Kotlin: A pragmatic language by JetBrainsKotlin: A pragmatic language by JetBrains
Kotlin: A pragmatic language by JetBrains
 

Recently uploaded

What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 

Recently uploaded (20)

Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 

Introduction to Kotlin for Android developers

  • 1.
  • 2. Introduction to Kotlin for android developers
  • 3. About me Mohamed Wael Senior Android developer @ Vodafone shared services Egypt. Computer Science 2015, Mansoura University. MohamedWael iMohamedWael MohamedWael
  • 4. Online Tools •Try Kotlin in your browser •Full Kotlin Reference •A list of Kotlin resources
  • 5. What is Kotlin •Kotlin is a cross-platform, statically typed, general- purpose programming language with type inference. •Developed by JetBrains, the creator of the android studio. •In October 2017, Kotlin is officially supported by Google for Android.
  • 6. What is Kotlin •Kotlin mainly targets the JVM, but also compiles to JavaScript or native code. •Kotlin is Open Source and it costs nothing to adopt. •Kotlin can be learned easily. It can be learned easily by simply reading the language reference. •The syntax is clean and intuitive(easy to use and understand). •Type inference allows its syntax to be more concise.
  • 7. Statically typed languages •A language is statically typed if the type of a variable is known at compile time. •The main advantage here is that all kinds of checking can be done by the compiler, and therefore a lot of trivial bugs are caught at a very early stage. •Examples: C, C++, Java, Rust, Go, Scala
  • 8.
  • 9. Statically typed languages /* Java Code */ static int num1, num2; //explicit declaration num1 = 20; //use the variables anywhere num2 = 30; /* Kotlin Code*/ val a: Int val b: Int a = 5 b = 10
  • 10. Benefits of Kotlin Language •Kotlin compiles to JVM bytecode or JavaScript: • Like Java, Bytecode is the compiled format for Kotlin programs also. • Bytecode means Programming code that, once compiled, is run through a virtual machine instead of the computer’s processor.
  • 11. Benefits of Kotlin Language •Kotlin compiles to JVM bytecode or JavaScript: • By using this approach, source code can be run on any platform once it has been compiled and run through the virtual machine. • Once a kotlin program has been converted to bytecode, it can be transferred across a network and executed by JVM(Java Virtual Machine).
  • 12. Benefits of Kotlin Language •Kotlin programs can use all existing Java Frameworks and Libraries: • Kotlin programs can use all existing java frameworks and libraries, even advanced frameworks that rely on annotation processing. • The main important thing about kotlin language is that it can easily integrate with Maven, Gradle and other build systems.
  • 13. Benefits of Kotlin Language •Kotlin’s null-safety is great •Now get rid of NullPointerException. This type of system helps us to avoid null pointer exceptions.
  • 14. Benefits of Kotlin Language •Kotlin’s null-safety is great •In Kotlin the system simply refuses to compile code that tries to assign or return null. Consider the following example: val name: String = null // tries to assign null, won’t compile. fun getName(): String = null // tries to return null, won’t compile.
  • 15. Benefits of Kotlin Language •But, what if we need nullability • In some special cases if we need nullability in our program then we have to ask Kotlin very nicely. • Every Nullable type require some special care and treatment. We can’t treat them the same way as non- nullable types and this is a very good thing.
  • 16. Benefits of Kotlin Language •But, what if we need nullability • We have to add “?” after the variable type. Kotlin also fails at compile-time whenever a NullPointerException may be thrown at run-time. Consider the following example val name: String? = null //assigned null and it will compile also. fun getName(): String? = null //returned null and it will compile too.
  • 17. Benefits of Kotlin Language •But, what if we need nullability /* won’t compile */ val name: String? = null val len = name.length /* correct way */ val name: String? = null val len = name?.length
  • 18. Kotlin file extention •Filename extensions of the Java are .java, .class, .jar but on the other hand filename extensions of the Kotlin are .kt and .kts.
  • 19.
  • 20. The entry point to a Kotlin •Like in Java, C and C++, the entry point to a Kotlin program is a function named “main”. Basically, it passed an array containing any command line arguments. •Consider the following example: //package level function, which return Unit //and takes an array of string as parameter fun main(args: Array<String>) { val scope = "world" println("Hello, $scope!") //semicolons are optional }
  • 21. Comments and package // Single-line comments start with // /* Multi-line comments look like this. */ // The "package" keyword works in the same way as in Java. package com.example.kotlin
  • 22. Declaring values and variables •Declaring values is done using either "var" or "val". •"val" declarations cannot be reassigned, whereas "vars" can.Consider the following example: val fooVal = 10 // we cannot later reassign fooVal to something else var fooVar = 10 fooVar = 20 // fooVar can be reassigned
  • 23. Type inference •In most cases, Kotlin can determine what the type of a variable is, so we don't have to explicitly specify it every time. We can explicitly declare the type of a variable like so: •Strings can be represented in a similar way as in Java. Escaping is done with a backslash. val foo: Int = 7 val fooString = "My String Is Here!" val barString = "Printing on a new line?nNo Problem!" val bazString = "Do you want to add a tab?tNo Problem!" println(fooString) println(barString) println(bazString)
  • 24. String representation •Strings can be represented in a similar way as in Java. Escaping is done with a backslash. val fooString = "My String Is Here!" val barString = "Printing on a new line?nNo Problem!" val bazString = "Do you want to add a tab?tNo Problem!" println(fooString) println(barString) println(bazString)
  • 25. String template expression •Strings can contain template expressions. •A template expression starts with a dollar sign ($). val fooTemplateString = "$fooString has ${fooString.length} characters" println(fooTemplateString) // => My String Is Here! has 18 characters
  • 26. Raw string •A raw string is delimited by a triple quote ("""). •Raw strings can contain newlines and any other characters. val fooRawString = """ fun helloWorld(val name : String) { println("Hello, world!") } """ println(fooRawString)
  • 27. Nullable Type •For a variable to hold null it must be explicitly specified as nullable. •A variable can be specified as nullable by appending a ? to its type. •We can access a nullable variable by using the ?. operator. •We can use the ?: operator to specify an alternative value to use if a variable is null.
  • 28. Nullable Type var fooNullable: String? = "abc" println(fooNullable?.length) // => 3 println(fooNullable?.length ?: -1) // => 3 fooNullable = null println(fooNullable?.length) // => null println(fooNullable?.length ?: -1) // => -1
  • 29. Functions declaration •Functions can be declared using the "fun" keyword. •Function arguments are specified in brackets after the function name. •Function arguments can optionally have a default value. •The function return type, if required, is specified after the arguments. fun hello(name: String = "world"): String { return "Hello, $name!" } println(hello("foo")) // => Hello, foo! println(hello(name = "bar")) // => Hello, bar! println(hello()) // => Hello, world!
  • 30. "vararg" keyword •A function parameter may be marked with the "vararg" keyword to allow a variable number of arguments to be passed to the function. fun varargExample(vararg names: Int) { println("Argument has ${names.size} elements") } varargExample() // => Argument has 0 elements varargExample(1) // => Argument has 1 elements varargExample(1, 2, 3) // => Argument has 3 elements
  • 31. Single expression function •When a function consists of a single expression then the curly brackets can be omitted. The body is specified after a = symbol. •If the return type can be inferred then we don't need to specify it. fun odd(x: Int): Boolean = x % 2 == 1 println(odd(6)) // => false println(odd(7)) // => true fun even(x: Int) = x % 2 == 0 println(even(6)) // => true println(even(7)) // => false
  • 32. Function return type inference •If the return type can be inferred then we don't need to specify it. fun even(x: Int) = x % 2 == 0 println(even(6)) // => true println(even(7)) // => false
  • 33. First-class citizen •In Kotlin, functions are first-class citizen. •It means that functions can be assigned to the variables, passed as an arguments or returned from another function. •While Kotlin is statically typed, to make it possible, functions need to have a type. It exists and it is called function type.
  • 34. Function Type • The function type that returns nothing useful (Unit) and takes no arguments. • The function type that returns Int and takes single argument of type Int. • The function type that returns another function that returns nothing useful (Unit). Both functions take no arguments. ()->Unit (Int)->Int ()->()->Unit
  • 35. Function Type •Function type is just a syntactic sugar for an interface, but the interface cannot be used explicitly. Nevertheless we can use function types like interfaces, what includes using them as type arguments or implementing them: class MyFunction : () -> Unit { override fun invoke() { println("I am called") } } fun main(args: Array<String>) { val function = MyFunction() function() // Prints: I am called }
  • 36. Function Type •We can also use them to type local variables, properties or arguments: val greet: () -> Unit val square: (Int) -> Int val producePrinter: () -> () -> Unit
  • 37. Function Type •Functions can take functions as arguments and return functions. •Named functions can be specified as arguments using the :: operator. fun not(f: (Int) -> Boolean): (Int) -> Boolean { return { n -> !f.invoke(n) } } val notOdd = not(::odd) val notEven = not(::even)
  • 38. The "class" keyword •The "class" keyword is used to declare classes. •To create a new instance we call the constructor. •Note that Kotlin does not have a "new" keyword. class ExampleClass(val x: Int) { fun memberFunction(y: Int): Int { return x + y } infix fun infixMemberFunction(y: Int): Int { return x * y } }
  • 39. Instantiating an object •To create a new instance we call the constructor. •Data classes are a concise way to create classes that just hold data. •The "hashCode"/"equals" and "toString" methods are automatically generated. val fooExampleClass = ExampleClass(7) // Member functions can be called using dot notation. println(fooExampleClass.memberFunction(4)) // => 11 data class DataClassExample(val x: Int, val y: Int, val z: Int) val fooData = DataClassExample(1, 2, 4) println(fooData) // => DataClassExample(x=1, y=2, z=4)
  • 40. Instantiating an object // Objects can be destructured into multiple variables. val (a, b, c) = fooCopy println("$a $b $c") // => 1 100 4 // destructuring in "for" loop for ((a, b, c) in listOf(fooData)) { println("$a $b $c") // => 1 100 4 } val mapData = mapOf("a" to 1, "b" to 2) // Map.Entry is destructurable as well for ((key, value) in mapData) { println("$key -> $value") }
  • 41. Kotlin functions •The "with" function is similar to the JavaScript "with" statement. data class MutableDataClassExample(var x: Int, var y: Int, var z: Int) val fooMutableData = MutableDataClassExample(7, 4, 9) with (fooMutableData) { x -= 2 y += 2 z-- } println(fooMutableData) // => MutableDataClassExample(x=5, y=6, z=8)
  • 42. The "listOf" function. /* We can create a list using the "listOf" function. The list will be immutable - elements cannot be added or removed. */ val fooList = listOf("a", "b", "c") println(fooList.size) // => 3 println(fooList.first()) // => a println(fooList.last()) // => c // Elements of a list can be accessed by their index. println(fooList[1]) // => b
  • 43. Kotlin functions // A mutable list can be created using the "mutableListOf" function. val fooMutableList = mutableListOf("a", "b", "c") fooMutableList.add("d") println(fooMutableList.last()) // => d println(fooMutableList.size) // => 4 // We can create a set using the "setOf" function. val fooSet = setOf("a", "b", "c") println(fooSet.contains("a")) // => true println(fooSet.contains("z")) // => false // We can create a map using the "mapOf" function. val fooMap = mapOf("a" to 8, "b" to 7, "c" to 9) // Map values can be accessed by their key. println(fooMap["a"]) // => 8
  • 44. Kotlin functions •An example of using a sequence to generate Fibonacci numbers, as below: /* Sequences represent lazily-evaluated collections. We can create a sequence using the "generateSequence" function. */ val fooSequence = generateSequence(1, { it + 1 }) val x = fooSequence.take(10).toList() println(x) // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  • 45. Kotlin functions fun fibonacciSequence(): Sequence<Long> { var a = 0L var b = 1L fun next(): Long { val result = a + b a = b b = result return a } return generateSequence(::next) } val y = fibonacciSequence().take(10).toList() println(y) // => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
  • 46. Kotlin functions •A higher order function is a function that accepts or return another function. •A "for" loop can be used with anything that provides an iterator. // Kotlin provides higher-order functions for working with collections. val z = (1..9).map { it * 3 } .filter { it < 20 } .groupBy { it % 2 == 0 } .mapKeys { if (it.key) "even" else "odd" } println(z) // => {odd=[3, 9, 15], even=[6, 12, 18]} for (c in "hello") { println(c) }
  • 47. Kotlin loops •A "for" loop can be used with anything that provides an iterator. •"while" loops work in the same way as other languages. for (c in "hello") { println(c) } var ctr = 0 while (ctr < 5) { println(ctr) ctr++ } //do-while do { println(ctr) ctr++ } while (ctr < 10)
  • 48. "if" expression •"if" can be used as an expression that returns a value. •For this reason the ternary ?: operator is not needed in Kotlin. val num = 5 val message = if (num % 2 == 0) "even" else "odd" println("$num is $message") // => 5 is odd
  • 49. " when" expression •"when" can be used as an alternative to "if-else if" chains. val i = 10 when { i < 7 -> println("first block") fooString.startsWith("hello") -> println("second block") else -> println("else block") }
  • 50. " when" expression // "when" can be used with an argument. when (i) { 0, 21 -> println("0 or 21") in 1..20 -> println("in the range 1 to 20") else -> println("none of the above") } // "when" can be used as a function that returns a value. var result = when (i) { 0, 21 -> "0 or 21" in 1..20 -> "in the range 1 to 20" else -> "none of the above" } println(result)
  • 51. The "is" operator •We can check if an object is of a particular type by using the "is" operator. •If an object passes a type check then it can be used as that type without explicitly casting it.
  • 52. The "is" operator fun smartCastExample(x: Any): Boolean { if (x is Boolean) { // x is automatically cast to Boolean return x } else if (x is Int) { // x is automatically cast to Int return x > 0 } else if (x is String) { // x is automatically cast to String return x.isNotEmpty() } else { return false } } println(smartCastExample("Hello, world!")) // => true println(smartCastExample("")) // => false println(smartCastExample(5)) // => true println(smartCastExample(0)) // => false println(smartCastExample(true)) // => true
  • 53. The "is" operator •Smartcast also works with when block // Smartcast also works with when block fun smartCastWhenExample(x: Any) = when (x) { is Boolean -> x is Int -> x > 0 is String -> x.isNotEmpty() else -> false }
  • 54. Extensions function •Extensions are a way to add new functionality to a class. •This is similar to C# extension methods. fun String.remove(c: Char): String { return this.filter { it != c } } println("Hello, world!".remove('l')) // => Heo, word!
  • 55. Enum classes // Enum classes are similar to Java enum types. enum class EnumExample { A, B, C } fun printEnum() = println(EnumExample.A) // => A
  • 56. The "object" keyword •The "object" keyword can be used to create singleton objects. •We cannot instantiate it but we can refer to its unique instance by its name. •This is similar to Scala singleton objects.
  • 57. The "object" keyword object ObjectExample { fun hello(): String { return "hello" } override fun toString(): String { return "Hello, it's me, ${ObjectExample::class.simpleName}" } } fun useSingletonObject() { println(ObjectExample.hello()) // => hello // In Kotlin, "Any" is the root of the class hierarchy, // just like "Object" is in Java val someRef: Any = ObjectExample println(someRef) // => Hello, it's me, ObjectExample }
  • 58. The "object" keyword •The not-null assertion operator (!!) converts any value to a non-null type and throws an exception if the value is null. var b: String? = "abc" val l = b!!.length
  • 59. Overloading operators •You can also overload operators through an extension methods.
  • 60. Overloadingoperators data class Counter(var value: Int) { // overload Counter += Int operator fun plusAssign(increment: Int) { this.value += increment } // overload Counter++ and ++Counter operator fun inc() = Counter(value + 1) // overload Counter + Counter operator fun plus(other: Counter) = Counter(this.value + other.value) // overload Counter * Counter operator fun times(other: Counter) = Counter(this.value * other.value) // overload Counter * Int operator fun times(value: Int) = Counter(this.value * value) // overload Counter in Counter operator fun contains(other: Counter) = other.value == this.value // overload Counter[Int] = Int operator fun set(index: Int, value: Int) { this.value = index + value } // overload Counter instance invocation operator fun invoke() = println("The value of the counter is $value") }
  • 61. Overloading operators // overload -Counter operator fun Counter.unaryMinus() = Counter(-this.value) fun operatorOverloadingDemo() { var counter1 = Counter(0) var counter2 = Counter(5) counter1 += 7 println(counter1) // => Counter(value=7) println(counter1 + counter2) // => Counter(value=12) println(counter1 * counter2) // => Counter(value=35) println(counter2 * 2) // => Counter(value=10) println(counter1 in Counter(5)) // => false println(counter1 in Counter(7)) // => true counter1[26] = 10 println(counter1) // => Counter(value=36) counter1() // => The value of the counter is 36 println(-counter2) // => Counter(value=-5) }
  • 62. Resources • https://kotlinlang.org/docs/reference/ • https://en.wikipedia.org/wiki/Kotlin_(programming_language) • https://stackoverflow.com/questions/1517582/what-is-the-difference-between- statically-typed-and-dynamically-typed-languages • https://www.xenonstack.com/blog/overview-kotlin-comparison-kotlin-java/ • https://blog.kotlin-academy.com/kotlin-programmer-dictionary-function-type-vs- function-literal-vs-lambda-expression-vs-anonymous-edc97e8873e • https://blog.kotlin-academy.com/kotlin-programmer-dictionary-2cb67fff1fe2 • https://medium.com/tompee/idiomatic-kotlin-higher-order-functions-and-function- types-adb59172796