SlideShare a Scribd company logo
Android
Development for
Advanced Beginners
Working with Kotlin
Basic Concepts
What is Kotlin?
•A language for Android development
•Official support: Google IO (2017)
•Currently in version 1.0
•Supports Java Frameworks/Libraries
•Kotlin files have a “.kt” extension
Kotlin Features
•Code is compiled to byte code
•Compile time code checking
•Run-time code checking
•Integrates with Maven, Gradle, etc
•IntelliJ automatically converts Java to Kotlin
Kotlin Features
• provides null safety
•Does not require “;” to separate statements
•Support for functions outside of classes
•Variables are first, then the variable type:
firstName: String
Kotlin Primitives
•Numeric: Double, Float, Long, Int, Short, Byte
•Other primitive types: Char, String, Boolean
•Conversion between types must be explicit
•+/-/*/ operator precedence: same as Java
A Kotlin “Hello World” Program
•Kotlin code:
fun main(args: Array<String>) {
println("Hello, World!")
}
•Java code:
public class HelloWorld1 {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Compiling a Kotlin Program
•Step 1: compile HelloWorld.kt:
kotlinc HelloWorld.kt -include-runtime -d HelloWorld.jar
•Step 2: notice the newly created JAR file:
HelloWorld.jar
•Step 3: launch HelloWorld:
java -jar HelloWorld.jar HelloWorld
•Output: Hello, World!
A Kotlin Program: Command Line Args
fun main(args: Array<String>) {
if (args.size < 2) {
println("Please enter a string")
return
}
println("Hello, ${args[1]}!")
}
Compiling a Kotlin Program
•Step 1: compile CommandLine1.kt:
kotlinc CommandLine1 -include-runtime -d CommandLine1.jar
•Step 2: notice the newly created JAR file:
CommandLine1.jar
•Step 3: launch CommandLine1:
java -jar CommandLine1.jar CommandLine1 Pasta
•Output: Hello, Pasta!
Kotlin Variables
•All variable declarations must be initialized
•'var' keyword: a variable that can be modified
•'val' keyword: a variable that cannot be modified
•A 'var' variable generates a getter and setter
•A 'val' variable generates only a getter
Kotlin Pointers
•Kotlin avoids the null pointer exception:
Use of the “Elvis” operator
•Sample code that compiles:
val name: String? = null
•Sample code that does not compile:
val name: String? = null
val namelen = name.length
Kotlin “val” Example
fun main(args: Array<String>) {
//val x1 : Int = 5
//val x2 : Int = 7
val x1 = 5
val x2 = 7
println("x1 = "+x1)
println("x2 = "+x2)
}
Output:
x1 = 5
x2 = 7
Kotlin “var” Example
fun main(args: Array<String>) {
var x1 : Int = 5
var x2 : Int = 7
var x3 = 13
var x4 = 22
val y1 = 8
val y2 = 2
Kotlin “var” Example
println("x1 = "+x1)
println("x2 = "+x2)
println("x3 = "+x3)
println("x4 = "+x4)
println("y1 = "+y1)
println("y2 = "+y2)
}
Exercise: compile and run this code sample
Kotlin Functions
•Unit-returning functions
•Single-Expression functions
•Variable argument functions
NB: If the compiler can infer the return type, then you do not
need to explicitly declare the return type.
Kotlin unit-returning Functions
•they do not return a value
•the return type is Unit
•Unit is optionally specified
•Example:
•fun printHello(name: String?) {
• print("hello")
•}
Kotlin Single-Expression Functions
•return a single expression
•the curly braces can be omitted
•the body is specified after an "=" symbol
•These 3 function definitions are equivalent:
fun triple(x: Int): Int {
return 3*x
}
fun triple(x: Int): Int = 3*x
fun triple(x: Int) = 3*x
Kotlin User-defined Functions
•def numberFunc(a, b):
• print (a,b)
•def stringFunc(a, b):
• print (a,b)
•numberFunc(3, 8)
•stringFunc('one', 'two')
Kotlin Functions with Default Values
•def numberFunc(a, b=10):
• print (a,b)
•def stringFunc(a, b='xyz'):
• print (a,b)
•numberFunc(3)
•stringFunc('one’)
Kotlin Lambda Expressions
What is a Lambda Expression?
•a way of representing a function
•a powerful feature in Kotlin
•simplifies Android development
Kotlin Lambda Expressions
Kotlin versus Java Lambda Expressions
Kotlin lambda expressions:
•can access/modify all variables that are in scope of their
declarations
Java 8 lambda expressions:
•can only access external variables but cannot modify them
Kotlin Lambda Expressions
fun main(args : Array<String>) {
val printHelloWorld = {
println("Hello, world!")
}
// two ways to print result:
printHelloWorld()
printHelloWorld.invoke()
}
Kotlin Lambda Expressions
fun main(args : Array<String>) {
val greet = { user: String ->
println("Good afternoon, $user")
}
greet("Sara")
val showAge = { user: String, age: Int ->
println("$user is $age")
}
showAge ("Steve", 35)
}
Kotlin Lambda Expressions
fun main(args : Array<String>) {
val max = { a: Int, b: Int ->
if (a > b)
a
else
b
}
println("max of 10 and 4 = "+max(10,4))
}
Kotlin Lambda Expressions
fun main(args : Array<String>) {
val add1 = {x: Int, y: Int -> x + y}
val add2 = {x: String, y: String -> x + y}
val x1 = add1(5,7)
val x2 = add2("Hello", "Kotlin")
println("x1 = "+x1)
println("x2 = "+x2)
}
Kotlin Lambda Expressions
fun main(args : Array<String>) {
val add1 = {x: String, y: String -> x + y}
val add2 = {x: String, y: Any -> x + y}
val add3 = {x: Any, y: Any -> x + y} // error
val x1 = add1("Hello", "Kotlin")
val x2 = add2("Hello", "Kotlin")
val x3 = add3("Hello", 123)
println("x1 = "+x1) // HelloKotlin
println("x2 = "+x2) // HelloKotlin
println("x3 = "+x3) // error
}
Kotlin Higher Order Functions
•What is a Function Type?
it’s a type consisting of:
• a function signature and
• a function return type
• separated by -> operator
Kotlin Higher Order Functions
•Function Type Examples:
•() -> Unit // returns Unit
•() -> String // returns String
•(String) -> Unit // returns Unit
•(String) -> Float // returns Float
Kotlin Higher Order Functions
fun main(args : Array<String>) {
fun Fn(a:Int, b:Int) : Int {
return a + b
}
val sum = Fn(3, 5)
println("sum = "+sum)
}
Kotlin Higher Order Functions
fun main(args : Array<String>) {
fun Fn(a:Int, b:Int, func:(a:Int, b:Int) -> Int) {
val result = func (a, b)
println("Fn result: $result")
}
// add is of type (Int,Int) -> Int:
val add = {x: Int, y: Int -> x + y}
Fn(3, 5, add)
}
Kotlin Higher Order Functions
fun main(args : Array<String>) {
fun Fn(a:Int, b:Int, func1:(a:Int, b:Int) -> Int), func2:(a:Int, b:Int) -> Int) {
val result = func1( func2(a, b), func1(a,b) ) // func1(4, 14)
println("Fn result: $result")
}
// add and sub are of type (Int,Int) -> Int:
val add = {x: Int, y: Int -> x + y}
val sub = {x: Int, y: Int -> x - y}
Fn(9, 5, add, sub)
}
Kotlin Higher Order Functions
• Kotlin Higher Order Functions:
• The counterpart to many “intermediate operators” in FRP
• Available in various collections:
• Arrays, collections, lists and iterators
• Support method chaining
• Avoid the need for intermediate variables
Kotlin Higher Order Functions
• Kotlin Arrays, collections, lists and iterators support the following functions/methods:
• all, any, appendString, contains, count, drop, dropWhile, dropWhileTo, filter, filterNot,
filterNotNull,
• filterNotNullTo, filterNotTo, filterTo, find, flatMap, flatMapTo, fold, foldRight, forEach,
• groupBy, groupByTo, makeString, map, mapTo, partition, plus, reduce, reduceRight,
requireNoNulls,
• reverse, sort, sortBy, take, takeWhile, takeWhileTo, toArray, toCollection, toLinkedList,
toList,
•toSet, toSortedList, toSortedSet
Kotlin Higher Order Functions
• Example: working with filters:
val nums = 1 . . 25
val evens = nums.filter { it % 2 == 0 }
val odds = nums.filter { it % 2 == 1 }
evens.forEach { n -> println(n) }
odds.forEach { n -> println(n) }
Kotlin Higher Order Functions
• Example: working with the map function:
val numList = 1 . . 5
val times2 = numList.map{ it * 2 }
times2.forEach{ n -> println($n) }
Kotlin Higher Order Functions
• Example: working with filters and maps:
val nums = 1 . . 5
val x = nums.filter { it % 2 == 0 }
.map{ it * 3 }
x.forEach { n -> println($n) }
Output: ?
Kotlin Higher Order Functions
• Example: working with filters and maps:
val nums = 1 . . 9
val x = nums.filter { it % 4 == 0 }
.map{ it * it }
x.forEach { n -> println($n) }
Output: 16, 64
val nums = 1 . . 9
val x = nums.map { it * it }
.filter { it % 4 == 0 }
x.forEach { n -> println($n) }
Output: 4, 16, 36, 64 // 1,4,9,16,25,36,49,64,81
Kotlin Higher Order Functions
• Example: working with reduce:
val numList = 1 . . 5
val sumList = numList.reduce { x, y -> x + y }
println("Reduce sumList = $sumList")
Kotlin Higher Order Functions
• Example: working with fold:
val numList = 1 . . 5
val sumList = numList.fold(0) { x, y -> x + y }
println("Fold sumList = $sumList")
Kotlin Recursion
• What is Recursion?
• A solution that is composed of smaller solutions of the same type
• Can be easier to define than its iterative counterpart
• Note: problems can have an iterative and recursive solution
• Example 1: the Tower of Hanoi
• Example 2: Sierpinski triangles
• Example 3: Mandelbrot Sets (fractals)
Kotlin Recursion
• What are Recursive Functions?
• Functions that are defined in terms of themselves
• Example 1: the factorial function
• Example 2: Fibonacci numbers
• Example 3: Euclid’s algorithm
• Example 4: Ackerman functions
Kotlin Recursion
• Add the first n integers: iterative solution
• fun main(args: Array<String>) {
• var num = 5
• var result:Int = 0
• for(i in 1..num) {
• result += i
• }
• print("The sum from 0 to "+num.toString()+" = "+result.toString()+"n")
•}
• NB: the closed form solution is n*(n+1)/2
Kotlin Recursion
•Add the first n integers: recursive solution
• fun main(args: Array<String>) {
• var num = 5
• var result:Int
• result = sum(num)
• print(num.toString()+" factorial = "+result.toString()+"n")
•}
•fun sum(num:Int): Int {
• if(num <= 1) return 1
• return num + sum(num-1)
•}
Kotlin Recursion
• Factorial function: iterative solution
• fun main(args: Array<String>) {
• var num = 5
• var result:Int = 1
• for(i in 1..num) {
• result *= i
• }
• print(num.toString()+" factorial = "+result.toString()+"n")
•}
Kotlin Recursion
•Factorial numbers: recursive solution
• fun main(args: Array<String>) {
• var num = 5
• var result:Int
• result = fact(num)
• print(num.toString()+" factorial = "+result.toString()+"n")
•}
•fun fact(num:Int): Int {
• if(num <= 1) return 1
• return num*fact(num-1)
•}
Kotlin Recursion
• Fibonacci numbers: recursive solution
• // F(0) = F(1) = 1
• // F(n) = F(n-1) + F(n-2)
• fun main(args: Array<String>) {
• var num = 5
• var result:Int
• result = F(num)
• print(" Fibonacci " +num.toString()+" factorial = " + result.toString()+ "n ")
•}
•fun F(num:Int): Int {
• if(num <= 1) return 1
• return F(num-1) + F(num-2)
•}
Kotlin Recursion
• Fibonacci numbers: iterative solution
• Exercise for you!
Kotlin Recursion
• Tail Recursion: factorial function
•fun main(args: Array<String>) {
• var num = 5
• var result:Int
• result = fact(num, 1)
• print(num.toString()+" factorial = "+result.toString()+"n")
•}
•fun fact(num:Int, prod:Int): Int {
• if(num <= 1) return prod
• return fact(num-1, num*prod)
•}

More Related Content

What's hot

Learning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardLearning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a Neckbeard
Kelsey Gilmore-Innis
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
Jonas Bonér
 
Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developers
Bartosz Kosarzycki
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
Maxim Novak
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Language
intelliyole
 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocaml
pramode_ce
 
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan s.r.o.
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScript
tmont
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
Mario Fusco
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
Bartosz Kosarzycki
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
NAVER Engineering
 
Intro to Functional Programming in Scala
Intro to Functional Programming in ScalaIntro to Functional Programming in Scala
Intro to Functional Programming in Scala
Shai Yallin
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
Mario Fusco
 
Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011
Andrey Breslav
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
Tomer Gabel
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
Shaul Rosenzwieg
 
3 kotlin vs. java- what kotlin has that java does not
3  kotlin vs. java- what kotlin has that java does not3  kotlin vs. java- what kotlin has that java does not
3 kotlin vs. java- what kotlin has that java does not
Sergey Bandysik
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015
Leonardo Borges
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
Mario Fusco
 
O caml2014 leroy-slides
O caml2014 leroy-slidesO caml2014 leroy-slides
O caml2014 leroy-slides
OCaml
 

What's hot (20)

Learning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardLearning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a Neckbeard
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developers
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Language
 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocaml
 
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScript
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 
Intro to Functional Programming in Scala
Intro to Functional Programming in ScalaIntro to Functional Programming in Scala
Intro to Functional Programming in Scala
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
 
Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 
3 kotlin vs. java- what kotlin has that java does not
3  kotlin vs. java- what kotlin has that java does not3  kotlin vs. java- what kotlin has that java does not
3 kotlin vs. java- what kotlin has that java does not
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
O caml2014 leroy-slides
O caml2014 leroy-slidesO caml2014 leroy-slides
O caml2014 leroy-slides
 

Similar to Introduction to Kotlin

Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Kotlin for Android Developers - 3
Kotlin for Android Developers - 3
Mohamed Nabil, MSc.
 
Intro to Kotlin
Intro to KotlinIntro to Kotlin
Intro to Kotlin
Magda Miu
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)
Cody Engel
 
Kotlin for backend development (Hackaburg 2018 Regensburg)
Kotlin for backend development (Hackaburg 2018 Regensburg)Kotlin for backend development (Hackaburg 2018 Regensburg)
Kotlin for backend development (Hackaburg 2018 Regensburg)
Tobias Schneck
 
Kotlin for Android devs
Kotlin for Android devsKotlin for Android devs
Kotlin for Android devs
Adit Lal
 
Kotlin on android
Kotlin on androidKotlin on android
Kotlin on android
Kurt Renzo Acosta
 
Kotlin boost yourproductivity
Kotlin boost yourproductivityKotlin boost yourproductivity
Kotlin boost yourproductivity
nklmish
 
Effective Java and Kotlin
Effective Java and KotlinEffective Java and Kotlin
Effective Java and Kotlin
경주 전
 
Kotlin 1.2: Sharing code between platforms
Kotlin 1.2: Sharing code between platformsKotlin 1.2: Sharing code between platforms
Kotlin 1.2: Sharing code between platforms
Kirill Rozov
 
Kotlin: Why Do You Care?
Kotlin: Why Do You Care?Kotlin: Why Do You Care?
Kotlin: Why Do You Care?
intelliyole
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016
Codemotion
 
JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)
Eduard Tomàs
 
Building Mobile Apps with Android
Building Mobile Apps with AndroidBuilding Mobile Apps with Android
Building Mobile Apps with Android
Kurt Renzo Acosta
 
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
Andrey Breslav
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, Swift
Yandex
 
Kotlin- Basic to Advance
Kotlin- Basic to Advance Kotlin- Basic to Advance
Kotlin- Basic to Advance
Coder Tech
 
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
Stuart Roebuck
 
A quick and fast intro to Kotlin
A quick and fast intro to Kotlin A quick and fast intro to Kotlin
A quick and fast intro to Kotlin
XPeppers
 
Kotlin
KotlinKotlin
Compose Code Camp (1).pptx
Compose Code Camp (1).pptxCompose Code Camp (1).pptx
Compose Code Camp (1).pptx
MadheswarKonidela
 

Similar to Introduction to Kotlin (20)

Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Kotlin for Android Developers - 3
Kotlin for Android Developers - 3
 
Intro to Kotlin
Intro to KotlinIntro to Kotlin
Intro to Kotlin
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)
 
Kotlin for backend development (Hackaburg 2018 Regensburg)
Kotlin for backend development (Hackaburg 2018 Regensburg)Kotlin for backend development (Hackaburg 2018 Regensburg)
Kotlin for backend development (Hackaburg 2018 Regensburg)
 
Kotlin for Android devs
Kotlin for Android devsKotlin for Android devs
Kotlin for Android devs
 
Kotlin on android
Kotlin on androidKotlin on android
Kotlin on android
 
Kotlin boost yourproductivity
Kotlin boost yourproductivityKotlin boost yourproductivity
Kotlin boost yourproductivity
 
Effective Java and Kotlin
Effective Java and KotlinEffective Java and Kotlin
Effective Java and Kotlin
 
Kotlin 1.2: Sharing code between platforms
Kotlin 1.2: Sharing code between platformsKotlin 1.2: Sharing code between platforms
Kotlin 1.2: Sharing code between platforms
 
Kotlin: Why Do You Care?
Kotlin: Why Do You Care?Kotlin: Why Do You Care?
Kotlin: Why Do You Care?
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016
 
JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)
 
Building Mobile Apps with Android
Building Mobile Apps with AndroidBuilding Mobile Apps with Android
Building Mobile Apps with Android
 
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, Swift
 
Kotlin- Basic to Advance
Kotlin- Basic to Advance Kotlin- Basic to Advance
Kotlin- Basic to Advance
 
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
 
A quick and fast intro to Kotlin
A quick and fast intro to Kotlin A quick and fast intro to Kotlin
A quick and fast intro to Kotlin
 
Kotlin
KotlinKotlin
Kotlin
 
Compose Code Camp (1).pptx
Compose Code Camp (1).pptxCompose Code Camp (1).pptx
Compose Code Camp (1).pptx
 

More from Oswald Campesato

Working with tf.data (TF 2)
Working with tf.data (TF 2)Working with tf.data (TF 2)
Working with tf.data (TF 2)
Oswald Campesato
 
Introduction to TensorFlow 2 and Keras
Introduction to TensorFlow 2 and KerasIntroduction to TensorFlow 2 and Keras
Introduction to TensorFlow 2 and Keras
Oswald Campesato
 
Introduction to Deep Learning
Introduction to Deep LearningIntroduction to Deep Learning
Introduction to Deep Learning
Oswald Campesato
 
Introduction to TensorFlow 2
Introduction to TensorFlow 2Introduction to TensorFlow 2
Introduction to TensorFlow 2
Oswald Campesato
 
Introduction to TensorFlow 2
Introduction to TensorFlow 2Introduction to TensorFlow 2
Introduction to TensorFlow 2
Oswald Campesato
 
"An Introduction to AI and Deep Learning"
"An Introduction to AI and Deep Learning""An Introduction to AI and Deep Learning"
"An Introduction to AI and Deep Learning"
Oswald Campesato
 
H2 o berkeleydltf
H2 o berkeleydltfH2 o berkeleydltf
H2 o berkeleydltf
Oswald Campesato
 
Introduction to Deep Learning, Keras, and Tensorflow
Introduction to Deep Learning, Keras, and TensorflowIntroduction to Deep Learning, Keras, and Tensorflow
Introduction to Deep Learning, Keras, and Tensorflow
Oswald Campesato
 
Introduction to Deep Learning for Non-Programmers
Introduction to Deep Learning for Non-ProgrammersIntroduction to Deep Learning for Non-Programmers
Introduction to Deep Learning for Non-Programmers
Oswald Campesato
 
TensorFlow in Your Browser
TensorFlow in Your BrowserTensorFlow in Your Browser
TensorFlow in Your Browser
Oswald Campesato
 
Deep Learning in Your Browser
Deep Learning in Your BrowserDeep Learning in Your Browser
Deep Learning in Your Browser
Oswald Campesato
 
Deep Learning and TensorFlow
Deep Learning and TensorFlowDeep Learning and TensorFlow
Deep Learning and TensorFlow
Oswald Campesato
 
Introduction to Deep Learning and TensorFlow
Introduction to Deep Learning and TensorFlowIntroduction to Deep Learning and TensorFlow
Introduction to Deep Learning and TensorFlow
Oswald Campesato
 
Intro to Deep Learning, TensorFlow, and tensorflow.js
Intro to Deep Learning, TensorFlow, and tensorflow.jsIntro to Deep Learning, TensorFlow, and tensorflow.js
Intro to Deep Learning, TensorFlow, and tensorflow.js
Oswald Campesato
 
Deep Learning and TensorFlow
Deep Learning and TensorFlowDeep Learning and TensorFlow
Deep Learning and TensorFlow
Oswald Campesato
 
Introduction to Deep Learning and Tensorflow
Introduction to Deep Learning and TensorflowIntroduction to Deep Learning and Tensorflow
Introduction to Deep Learning and Tensorflow
Oswald Campesato
 
Deep Learning, Scala, and Spark
Deep Learning, Scala, and SparkDeep Learning, Scala, and Spark
Deep Learning, Scala, and Spark
Oswald Campesato
 
Deep Learning in your Browser: powered by WebGL
Deep Learning in your Browser: powered by WebGLDeep Learning in your Browser: powered by WebGL
Deep Learning in your Browser: powered by WebGL
Oswald Campesato
 
Deep Learning, Keras, and TensorFlow
Deep Learning, Keras, and TensorFlowDeep Learning, Keras, and TensorFlow
Deep Learning, Keras, and TensorFlow
Oswald Campesato
 
C++ and Deep Learning
C++ and Deep LearningC++ and Deep Learning
C++ and Deep Learning
Oswald Campesato
 

More from Oswald Campesato (20)

Working with tf.data (TF 2)
Working with tf.data (TF 2)Working with tf.data (TF 2)
Working with tf.data (TF 2)
 
Introduction to TensorFlow 2 and Keras
Introduction to TensorFlow 2 and KerasIntroduction to TensorFlow 2 and Keras
Introduction to TensorFlow 2 and Keras
 
Introduction to Deep Learning
Introduction to Deep LearningIntroduction to Deep Learning
Introduction to Deep Learning
 
Introduction to TensorFlow 2
Introduction to TensorFlow 2Introduction to TensorFlow 2
Introduction to TensorFlow 2
 
Introduction to TensorFlow 2
Introduction to TensorFlow 2Introduction to TensorFlow 2
Introduction to TensorFlow 2
 
"An Introduction to AI and Deep Learning"
"An Introduction to AI and Deep Learning""An Introduction to AI and Deep Learning"
"An Introduction to AI and Deep Learning"
 
H2 o berkeleydltf
H2 o berkeleydltfH2 o berkeleydltf
H2 o berkeleydltf
 
Introduction to Deep Learning, Keras, and Tensorflow
Introduction to Deep Learning, Keras, and TensorflowIntroduction to Deep Learning, Keras, and Tensorflow
Introduction to Deep Learning, Keras, and Tensorflow
 
Introduction to Deep Learning for Non-Programmers
Introduction to Deep Learning for Non-ProgrammersIntroduction to Deep Learning for Non-Programmers
Introduction to Deep Learning for Non-Programmers
 
TensorFlow in Your Browser
TensorFlow in Your BrowserTensorFlow in Your Browser
TensorFlow in Your Browser
 
Deep Learning in Your Browser
Deep Learning in Your BrowserDeep Learning in Your Browser
Deep Learning in Your Browser
 
Deep Learning and TensorFlow
Deep Learning and TensorFlowDeep Learning and TensorFlow
Deep Learning and TensorFlow
 
Introduction to Deep Learning and TensorFlow
Introduction to Deep Learning and TensorFlowIntroduction to Deep Learning and TensorFlow
Introduction to Deep Learning and TensorFlow
 
Intro to Deep Learning, TensorFlow, and tensorflow.js
Intro to Deep Learning, TensorFlow, and tensorflow.jsIntro to Deep Learning, TensorFlow, and tensorflow.js
Intro to Deep Learning, TensorFlow, and tensorflow.js
 
Deep Learning and TensorFlow
Deep Learning and TensorFlowDeep Learning and TensorFlow
Deep Learning and TensorFlow
 
Introduction to Deep Learning and Tensorflow
Introduction to Deep Learning and TensorflowIntroduction to Deep Learning and Tensorflow
Introduction to Deep Learning and Tensorflow
 
Deep Learning, Scala, and Spark
Deep Learning, Scala, and SparkDeep Learning, Scala, and Spark
Deep Learning, Scala, and Spark
 
Deep Learning in your Browser: powered by WebGL
Deep Learning in your Browser: powered by WebGLDeep Learning in your Browser: powered by WebGL
Deep Learning in your Browser: powered by WebGL
 
Deep Learning, Keras, and TensorFlow
Deep Learning, Keras, and TensorFlowDeep Learning, Keras, and TensorFlow
Deep Learning, Keras, and TensorFlow
 
C++ and Deep Learning
C++ and Deep LearningC++ and Deep Learning
C++ and Deep Learning
 

Recently uploaded

Liberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptxLiberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptx
Massimo Artizzu
 
Transforming Product Development using OnePlan To Boost Efficiency and Innova...
Transforming Product Development using OnePlan To Boost Efficiency and Innova...Transforming Product Development using OnePlan To Boost Efficiency and Innova...
Transforming Product Development using OnePlan To Boost Efficiency and Innova...
OnePlan Solutions
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
Bert Jan Schrijver
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
sjcobrien
 
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data PlatformAlluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio, Inc.
 
What’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete RoadmapWhat’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete Roadmap
Envertis Software Solutions
 
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptxMigration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
ervikas4
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
Patrick Weigel
 
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
widenerjobeyrl638
 
Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...
Paul Brebner
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Paul Brebner
 
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptxOperational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
sandeepmenon62
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
kalichargn70th171
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
Tier1 app
 
42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert
vaishalijagtap12
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
ShulagnaSarkar2
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
ToXSL Technologies
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
safelyiotech
 
TMU毕业证书精仿办理
TMU毕业证书精仿办理TMU毕业证书精仿办理
TMU毕业证书精仿办理
aeeva
 

Recently uploaded (20)

Liberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptxLiberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptx
 
Transforming Product Development using OnePlan To Boost Efficiency and Innova...
Transforming Product Development using OnePlan To Boost Efficiency and Innova...Transforming Product Development using OnePlan To Boost Efficiency and Innova...
Transforming Product Development using OnePlan To Boost Efficiency and Innova...
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
 
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data PlatformAlluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
 
What’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete RoadmapWhat’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete Roadmap
 
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptxMigration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
 
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
 
Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
 
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptxOperational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
 
42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
 
TMU毕业证书精仿办理
TMU毕业证书精仿办理TMU毕业证书精仿办理
TMU毕业证书精仿办理
 

Introduction to Kotlin

  • 2. What is Kotlin? •A language for Android development •Official support: Google IO (2017) •Currently in version 1.0 •Supports Java Frameworks/Libraries •Kotlin files have a “.kt” extension
  • 3. Kotlin Features •Code is compiled to byte code •Compile time code checking •Run-time code checking •Integrates with Maven, Gradle, etc •IntelliJ automatically converts Java to Kotlin
  • 4. Kotlin Features • provides null safety •Does not require “;” to separate statements •Support for functions outside of classes •Variables are first, then the variable type: firstName: String
  • 5. Kotlin Primitives •Numeric: Double, Float, Long, Int, Short, Byte •Other primitive types: Char, String, Boolean •Conversion between types must be explicit •+/-/*/ operator precedence: same as Java
  • 6. A Kotlin “Hello World” Program •Kotlin code: fun main(args: Array<String>) { println("Hello, World!") } •Java code: public class HelloWorld1 { public static void main(String[] args) { System.out.println("Hello, World!"); } }
  • 7. Compiling a Kotlin Program •Step 1: compile HelloWorld.kt: kotlinc HelloWorld.kt -include-runtime -d HelloWorld.jar •Step 2: notice the newly created JAR file: HelloWorld.jar •Step 3: launch HelloWorld: java -jar HelloWorld.jar HelloWorld •Output: Hello, World!
  • 8. A Kotlin Program: Command Line Args fun main(args: Array<String>) { if (args.size < 2) { println("Please enter a string") return } println("Hello, ${args[1]}!") }
  • 9. Compiling a Kotlin Program •Step 1: compile CommandLine1.kt: kotlinc CommandLine1 -include-runtime -d CommandLine1.jar •Step 2: notice the newly created JAR file: CommandLine1.jar •Step 3: launch CommandLine1: java -jar CommandLine1.jar CommandLine1 Pasta •Output: Hello, Pasta!
  • 10. Kotlin Variables •All variable declarations must be initialized •'var' keyword: a variable that can be modified •'val' keyword: a variable that cannot be modified •A 'var' variable generates a getter and setter •A 'val' variable generates only a getter
  • 11. Kotlin Pointers •Kotlin avoids the null pointer exception: Use of the “Elvis” operator •Sample code that compiles: val name: String? = null •Sample code that does not compile: val name: String? = null val namelen = name.length
  • 12. Kotlin “val” Example fun main(args: Array<String>) { //val x1 : Int = 5 //val x2 : Int = 7 val x1 = 5 val x2 = 7 println("x1 = "+x1) println("x2 = "+x2) } Output: x1 = 5 x2 = 7
  • 13. Kotlin “var” Example fun main(args: Array<String>) { var x1 : Int = 5 var x2 : Int = 7 var x3 = 13 var x4 = 22 val y1 = 8 val y2 = 2
  • 14. Kotlin “var” Example println("x1 = "+x1) println("x2 = "+x2) println("x3 = "+x3) println("x4 = "+x4) println("y1 = "+y1) println("y2 = "+y2) } Exercise: compile and run this code sample
  • 15. Kotlin Functions •Unit-returning functions •Single-Expression functions •Variable argument functions NB: If the compiler can infer the return type, then you do not need to explicitly declare the return type.
  • 16. Kotlin unit-returning Functions •they do not return a value •the return type is Unit •Unit is optionally specified •Example: •fun printHello(name: String?) { • print("hello") •}
  • 17. Kotlin Single-Expression Functions •return a single expression •the curly braces can be omitted •the body is specified after an "=" symbol •These 3 function definitions are equivalent: fun triple(x: Int): Int { return 3*x } fun triple(x: Int): Int = 3*x fun triple(x: Int) = 3*x
  • 18. Kotlin User-defined Functions •def numberFunc(a, b): • print (a,b) •def stringFunc(a, b): • print (a,b) •numberFunc(3, 8) •stringFunc('one', 'two')
  • 19. Kotlin Functions with Default Values •def numberFunc(a, b=10): • print (a,b) •def stringFunc(a, b='xyz'): • print (a,b) •numberFunc(3) •stringFunc('one’)
  • 20. Kotlin Lambda Expressions What is a Lambda Expression? •a way of representing a function •a powerful feature in Kotlin •simplifies Android development
  • 21. Kotlin Lambda Expressions Kotlin versus Java Lambda Expressions Kotlin lambda expressions: •can access/modify all variables that are in scope of their declarations Java 8 lambda expressions: •can only access external variables but cannot modify them
  • 22. Kotlin Lambda Expressions fun main(args : Array<String>) { val printHelloWorld = { println("Hello, world!") } // two ways to print result: printHelloWorld() printHelloWorld.invoke() }
  • 23. Kotlin Lambda Expressions fun main(args : Array<String>) { val greet = { user: String -> println("Good afternoon, $user") } greet("Sara") val showAge = { user: String, age: Int -> println("$user is $age") } showAge ("Steve", 35) }
  • 24. Kotlin Lambda Expressions fun main(args : Array<String>) { val max = { a: Int, b: Int -> if (a > b) a else b } println("max of 10 and 4 = "+max(10,4)) }
  • 25. Kotlin Lambda Expressions fun main(args : Array<String>) { val add1 = {x: Int, y: Int -> x + y} val add2 = {x: String, y: String -> x + y} val x1 = add1(5,7) val x2 = add2("Hello", "Kotlin") println("x1 = "+x1) println("x2 = "+x2) }
  • 26. Kotlin Lambda Expressions fun main(args : Array<String>) { val add1 = {x: String, y: String -> x + y} val add2 = {x: String, y: Any -> x + y} val add3 = {x: Any, y: Any -> x + y} // error val x1 = add1("Hello", "Kotlin") val x2 = add2("Hello", "Kotlin") val x3 = add3("Hello", 123) println("x1 = "+x1) // HelloKotlin println("x2 = "+x2) // HelloKotlin println("x3 = "+x3) // error }
  • 27. Kotlin Higher Order Functions •What is a Function Type? it’s a type consisting of: • a function signature and • a function return type • separated by -> operator
  • 28. Kotlin Higher Order Functions •Function Type Examples: •() -> Unit // returns Unit •() -> String // returns String •(String) -> Unit // returns Unit •(String) -> Float // returns Float
  • 29. Kotlin Higher Order Functions fun main(args : Array<String>) { fun Fn(a:Int, b:Int) : Int { return a + b } val sum = Fn(3, 5) println("sum = "+sum) }
  • 30. Kotlin Higher Order Functions fun main(args : Array<String>) { fun Fn(a:Int, b:Int, func:(a:Int, b:Int) -> Int) { val result = func (a, b) println("Fn result: $result") } // add is of type (Int,Int) -> Int: val add = {x: Int, y: Int -> x + y} Fn(3, 5, add) }
  • 31. Kotlin Higher Order Functions fun main(args : Array<String>) { fun Fn(a:Int, b:Int, func1:(a:Int, b:Int) -> Int), func2:(a:Int, b:Int) -> Int) { val result = func1( func2(a, b), func1(a,b) ) // func1(4, 14) println("Fn result: $result") } // add and sub are of type (Int,Int) -> Int: val add = {x: Int, y: Int -> x + y} val sub = {x: Int, y: Int -> x - y} Fn(9, 5, add, sub) }
  • 32. Kotlin Higher Order Functions • Kotlin Higher Order Functions: • The counterpart to many “intermediate operators” in FRP • Available in various collections: • Arrays, collections, lists and iterators • Support method chaining • Avoid the need for intermediate variables
  • 33. Kotlin Higher Order Functions • Kotlin Arrays, collections, lists and iterators support the following functions/methods: • all, any, appendString, contains, count, drop, dropWhile, dropWhileTo, filter, filterNot, filterNotNull, • filterNotNullTo, filterNotTo, filterTo, find, flatMap, flatMapTo, fold, foldRight, forEach, • groupBy, groupByTo, makeString, map, mapTo, partition, plus, reduce, reduceRight, requireNoNulls, • reverse, sort, sortBy, take, takeWhile, takeWhileTo, toArray, toCollection, toLinkedList, toList, •toSet, toSortedList, toSortedSet
  • 34. Kotlin Higher Order Functions • Example: working with filters: val nums = 1 . . 25 val evens = nums.filter { it % 2 == 0 } val odds = nums.filter { it % 2 == 1 } evens.forEach { n -> println(n) } odds.forEach { n -> println(n) }
  • 35. Kotlin Higher Order Functions • Example: working with the map function: val numList = 1 . . 5 val times2 = numList.map{ it * 2 } times2.forEach{ n -> println($n) }
  • 36. Kotlin Higher Order Functions • Example: working with filters and maps: val nums = 1 . . 5 val x = nums.filter { it % 2 == 0 } .map{ it * 3 } x.forEach { n -> println($n) } Output: ?
  • 37. Kotlin Higher Order Functions • Example: working with filters and maps: val nums = 1 . . 9 val x = nums.filter { it % 4 == 0 } .map{ it * it } x.forEach { n -> println($n) } Output: 16, 64 val nums = 1 . . 9 val x = nums.map { it * it } .filter { it % 4 == 0 } x.forEach { n -> println($n) } Output: 4, 16, 36, 64 // 1,4,9,16,25,36,49,64,81
  • 38. Kotlin Higher Order Functions • Example: working with reduce: val numList = 1 . . 5 val sumList = numList.reduce { x, y -> x + y } println("Reduce sumList = $sumList")
  • 39. Kotlin Higher Order Functions • Example: working with fold: val numList = 1 . . 5 val sumList = numList.fold(0) { x, y -> x + y } println("Fold sumList = $sumList")
  • 40. Kotlin Recursion • What is Recursion? • A solution that is composed of smaller solutions of the same type • Can be easier to define than its iterative counterpart • Note: problems can have an iterative and recursive solution • Example 1: the Tower of Hanoi • Example 2: Sierpinski triangles • Example 3: Mandelbrot Sets (fractals)
  • 41. Kotlin Recursion • What are Recursive Functions? • Functions that are defined in terms of themselves • Example 1: the factorial function • Example 2: Fibonacci numbers • Example 3: Euclid’s algorithm • Example 4: Ackerman functions
  • 42. Kotlin Recursion • Add the first n integers: iterative solution • fun main(args: Array<String>) { • var num = 5 • var result:Int = 0 • for(i in 1..num) { • result += i • } • print("The sum from 0 to "+num.toString()+" = "+result.toString()+"n") •} • NB: the closed form solution is n*(n+1)/2
  • 43. Kotlin Recursion •Add the first n integers: recursive solution • fun main(args: Array<String>) { • var num = 5 • var result:Int • result = sum(num) • print(num.toString()+" factorial = "+result.toString()+"n") •} •fun sum(num:Int): Int { • if(num <= 1) return 1 • return num + sum(num-1) •}
  • 44. Kotlin Recursion • Factorial function: iterative solution • fun main(args: Array<String>) { • var num = 5 • var result:Int = 1 • for(i in 1..num) { • result *= i • } • print(num.toString()+" factorial = "+result.toString()+"n") •}
  • 45. Kotlin Recursion •Factorial numbers: recursive solution • fun main(args: Array<String>) { • var num = 5 • var result:Int • result = fact(num) • print(num.toString()+" factorial = "+result.toString()+"n") •} •fun fact(num:Int): Int { • if(num <= 1) return 1 • return num*fact(num-1) •}
  • 46. Kotlin Recursion • Fibonacci numbers: recursive solution • // F(0) = F(1) = 1 • // F(n) = F(n-1) + F(n-2) • fun main(args: Array<String>) { • var num = 5 • var result:Int • result = F(num) • print(" Fibonacci " +num.toString()+" factorial = " + result.toString()+ "n ") •} •fun F(num:Int): Int { • if(num <= 1) return 1 • return F(num-1) + F(num-2) •}
  • 47. Kotlin Recursion • Fibonacci numbers: iterative solution • Exercise for you!
  • 48. Kotlin Recursion • Tail Recursion: factorial function •fun main(args: Array<String>) { • var num = 5 • var result:Int • result = fact(num, 1) • print(num.toString()+" factorial = "+result.toString()+"n") •} •fun fact(num:Int, prod:Int): Int { • if(num <= 1) return prod • return fact(num-1, num*prod) •}