SlideShare a Scribd company logo
Kotlin for Android
May 24, 2018
y/kotlin-workbook
Functions
Operators, Extensions, Inline, Infix, Interop
y/kotlin-workbook
● Almost every operator in Kotlin is mapped to a function
Operators
FUNCTIONS
y/kotlin-workbook
Expression Translates to
a + b a.plus(b)
a..b a.rangeTo(b)
a in b b.contains(a)
a !in b !b.contains(a)
a[i] a.get(i)
a[i] = b a.set(i, b)
a() a.invoke()
a(i_1, ..., i_n) a.invoke(i_1, ..., i_n)
a += b a.plusAssign(b)
a == b a?.equals(b) ?: (b === null)
a != b !(a?.equals(b) ?: (b === null))
a > b a.compareTo(b) > 0
● A class can extend from a function
Functions Are Types
FUNCTIONS
y/kotlin-workbook
fun world(): String {
return "World"
}
fun world(): String = "World"
fun world() = "World"Basic Syntax
FUNCTIONS
y/kotlin-workbook
In depth
FUNCTIONS
fun world() = "World"
object World : () -> String {
override fun invoke(): String {
return "World"
}
}
y/kotlin-workbook
In depth
FUNCTIONS
fun world() = "World"
object World : () -> String {
override fun invoke(): String {
return "World"
}
}
y/kotlin-workbook
In depth
FUNCTIONS
fun world() = "World"
object World : () -> String {
override fun invoke() = "World"
}
fun hello(who: () -> String) {
println("Hello ${who()}!")
}
hello({ "World" })
y/kotlin-workbook
In depth
FUNCTIONS
fun world() = "World"
object World : () -> String {
override fun invoke() = "World"
}
fun hello(who: () -> String) {
println("Hello ${who()}!")
}
hello { "World" }
y/kotlin-workbook
In depth
FUNCTIONS
fun world() = "World"
object World : () -> String {
override fun invoke() = "World"
}
fun hello(who: () -> String) {
println("Hello ${who()}!")
}
hello { "World" }
hello(::world)
hello(World)
y/kotlin-workbook
In depth
FUNCTIONS
fun world() = "World"
object World : () -> String {
override fun invoke() = "World"
}
fun hello(who: () -> String) {
println("Hello ${who()}!")
}
hello({ "World" }::invoke::invoke)
hello(::world::invoke::invoke::invoke)
hello(World::invoke::invoke::invoke::invoke::invoke)
y/kotlin-workbook
typealias NameProvider = () -> String
typealias DeviceName = () -> String
fun hello(who: NameProvider, what: DeviceName) {
println("Hello ${who()} on ${what()}!")
}
Functions Are Types
typealias
FUNCTIONS
y/kotlin-workbook
Functions Are Types
typealias
FUNCTIONS typealias NameProvider = () -> String
typealias DeviceName = () -> String
fun hello(who: NameProvider, what: DeviceName) {
println("Hello ${who()} on ${what()}!")
}
object World : NameProvider {
override fun invoke() = "World"
}
object Device : DeviceName {
override fun invoke() = "Android"
}
y/kotlin-workbook
Functions Are Types
typealias Warning
FUNCTIONS typealias NameProvider = () -> String
typealias DeviceName = () -> String
fun hello(who: NameProvider, what: DeviceName) {
println("Hello ${who()} on ${what()}!")
}
object World : NameProvider {
override fun invoke() = "World"
}
object Device : DeviceName {
override fun invoke() = "Android"
}
hello(World, Device) // "Hello World on Android!"
hello(Device, World) // "Hello Android on World!"
hello(what = Device, who = World)
y/kotlin-workbook
hello(what = Device, who = World)
● You can reorder the arguments you supply when invoking a
function if you use their names
● Works only for functions and constructors defined in Kotlin
Named Parameters
FUNCTIONS
y/kotlin-workbook
● Commonly known as extension functions
● Declares receiver type together with its name
● this in the body refers to an instance of the receiver
● Calling from Java the receiver is the first argument
Functions with
Receivers
FUNCTIONS
y/kotlin-workbook
Functions with
Receivers
FUNCTIONS
// Kotlin
fun ViewGroup.foo(): String
// Java
public static String foo(ViewGroup dis)
y/kotlin-workbook
Functions with
Receivers
FUNCTIONS
// Kotlin
fun ViewGroup.foo(bar: Baz): String
// Java
public static String foo(ViewGroup dis, Baz bar)
y/kotlin-workbook
Functions with
Receivers
FUNCTIONS
class Potato {
fun ViewGroup.foo(bar: Baz): String {
(this is ViewGroup) == true
(this@Potato is Potato) == true
}
}
y/kotlin-workbook
Functions with
Receivers
FUNCTIONS
val container: ViewGroup = ...
container += R.layout.scroll_view
y/kotlin-workbook
Functions with
Receivers
FUNCTIONS
val container: ViewGroup = ...
container += R.layout.scroll_view
operator fun ViewGroup.plusAssign(
@LayoutRes layout: Int
) {
LayoutInflater
.from(this.context)
.inflate(layout, this, true)
}
y/kotlin-workbook
Higher Order Functions
FUNCTIONS
fun hi(who: () -> String) = println("Hi ${who()}!")
hi { "World" } // prints Hi World!
fun hi(who: String, where: () -> String) {
println("Hi $who from ${where()}!")
}
hi("Gesh") { "Hamburg" } // prints Hi Gesh from Hamburg!
y/kotlin-workbook
● Improved syntax if the last argument of a function is a
function
Vararg Functions
FUNCTIONS
fun main(vararg args: String)
// Java
public void main(String... args)
y/kotlin-workbook
● vararg keyword
● Only one per function
● Usually last unless a higher order function
Array Spread Operator
FUNCTIONS
fun main(vararg args: String)
// Java
public void main(String... args)
val array = arrayOf(1, 2) // [1, 2]
val list1 = listOf(array) // [[1, 2]]
val list2 = listOf(*array) // [1, 2]
val list3 = listOf(0, array, 3) // [0, [1, 2], 3]
val list4 = listOf(0, *array, 3) // [0, 1, 2, 3]
y/kotlin-workbook
● vararg keyword
● Only one per function
● Usually last unless a higher order function
● Spread an existing array into multiple vararg arguments
Infix Functions
FUNCTIONS
infix fun <A, B> A.to(that: B) = Pair(this, that)
mapOf(
"a" to "b",
"a".to("b"),
Pair("a", "b")
)
y/kotlin-workbook
● Member or extension functions
● Exactly one argument
Inline Functions
FUNCTIONS
y/kotlin-workbook
● Compiler will inline the body at the call-site
● Cannot be used from Java
Inline Functions
FUNCTIONS
// Java
ViewModel model = mock(ViewModel.class)
// Kotlin
val model: ViewModel = mock(ViewModel::class.java)y/kotlin-workbook
● Compiler will inline the body at the call-site
● Cannot be used from Java
● Can use reified generics
Inline Functions
FUNCTIONS
// Java
ViewModel model = mock(ViewModel.class)
inline fun <reified T> mock(): T {
return Mockito.mock(T::class.java) as T
}
// Kotlin
val model: ViewModel = mock()
val model = mock<ViewModel>()
y/kotlin-workbook
● Compiler will inline the body at the call-site
● Cannot be used from Java
● Can use reified generics
Questions?
Next Up: Lunch
After Luch: Properties

More Related Content

What's hot

미려한 UI/UX를 위한 여정
미려한 UI/UX를 위한 여정미려한 UI/UX를 위한 여정
미려한 UI/UX를 위한 여정
SeungChul Kang
 
Txjs
TxjsTxjs
Swift Rocks #2: Going functional
Swift Rocks #2: Going functionalSwift Rocks #2: Going functional
Swift Rocks #2: Going functional
Hackraft
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
John De Goes
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScript
Garth Gilmour
 
JavaScript ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
Leo Hernandez
 
Why Kotlin makes Java null and void
Why Kotlin makes Java null and voidWhy Kotlin makes Java null and void
Why Kotlin makes Java null and void
Chetan Padia
 
Minimizing Decision Fatigue to Improve Team Productivity
Minimizing Decision Fatigue to Improve Team ProductivityMinimizing Decision Fatigue to Improve Team Productivity
Minimizing Decision Fatigue to Improve Team Productivity
Derek Lee Boire
 
Atomically { Delete Your Actors }
Atomically { Delete Your Actors }Atomically { Delete Your Actors }
Atomically { Delete Your Actors }
John De Goes
 
2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.js2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.js
Noritada Shimizu
 
Writing Clean Code in Swift
Writing Clean Code in SwiftWriting Clean Code in Swift
Writing Clean Code in Swift
Derek Lee Boire
 
20151224-games
20151224-games20151224-games
20151224-games
Noritada Shimizu
 
JIP Pipeline System Introduction
JIP Pipeline System IntroductionJIP Pipeline System Introduction
JIP Pipeline System Introduction
thasso23
 
Functional pe(a)rls: Huey's zipper
Functional pe(a)rls: Huey's zipperFunctional pe(a)rls: Huey's zipper
Functional pe(a)rls: Huey's zipper
osfameron
 
Haskell in the Real World
Haskell in the Real WorldHaskell in the Real World
Haskell in the Real World
osfameron
 
Streams for (Co)Free!
Streams for (Co)Free!Streams for (Co)Free!
Streams for (Co)Free!
John De Goes
 
EuroPython 2017 - Bonono - Simple ETL in python 3.5+
EuroPython 2017 - Bonono - Simple ETL in python 3.5+EuroPython 2017 - Bonono - Simple ETL in python 3.5+
EuroPython 2017 - Bonono - Simple ETL in python 3.5+
Romain Dorgueil
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Development
vito jeng
 
Introduction of ES2015
Introduction of ES2015Introduction of ES2015
Introduction of ES2015
Nakajima Shigeru
 

What's hot (20)

미려한 UI/UX를 위한 여정
미려한 UI/UX를 위한 여정미려한 UI/UX를 위한 여정
미려한 UI/UX를 위한 여정
 
Txjs
TxjsTxjs
Txjs
 
Swift Rocks #2: Going functional
Swift Rocks #2: Going functionalSwift Rocks #2: Going functional
Swift Rocks #2: Going functional
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScript
 
JavaScript ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
 
Why Kotlin makes Java null and void
Why Kotlin makes Java null and voidWhy Kotlin makes Java null and void
Why Kotlin makes Java null and void
 
Minimizing Decision Fatigue to Improve Team Productivity
Minimizing Decision Fatigue to Improve Team ProductivityMinimizing Decision Fatigue to Improve Team Productivity
Minimizing Decision Fatigue to Improve Team Productivity
 
Atomically { Delete Your Actors }
Atomically { Delete Your Actors }Atomically { Delete Your Actors }
Atomically { Delete Your Actors }
 
2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.js2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.js
 
ProgrammingwithGOLang
ProgrammingwithGOLangProgrammingwithGOLang
ProgrammingwithGOLang
 
Writing Clean Code in Swift
Writing Clean Code in SwiftWriting Clean Code in Swift
Writing Clean Code in Swift
 
20151224-games
20151224-games20151224-games
20151224-games
 
JIP Pipeline System Introduction
JIP Pipeline System IntroductionJIP Pipeline System Introduction
JIP Pipeline System Introduction
 
Functional pe(a)rls: Huey's zipper
Functional pe(a)rls: Huey's zipperFunctional pe(a)rls: Huey's zipper
Functional pe(a)rls: Huey's zipper
 
Haskell in the Real World
Haskell in the Real WorldHaskell in the Real World
Haskell in the Real World
 
Streams for (Co)Free!
Streams for (Co)Free!Streams for (Co)Free!
Streams for (Co)Free!
 
EuroPython 2017 - Bonono - Simple ETL in python 3.5+
EuroPython 2017 - Bonono - Simple ETL in python 3.5+EuroPython 2017 - Bonono - Simple ETL in python 3.5+
EuroPython 2017 - Bonono - Simple ETL in python 3.5+
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Development
 
Introduction of ES2015
Introduction of ES2015Introduction of ES2015
Introduction of ES2015
 

Similar to Kotlin For Android - Functions (part 3 of 7)

What's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritageWhat's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritage
DroidConTLV
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
Tim Underwood
 
Kotlin
KotlinKotlin
GoCracow #5 Bartlomiej klimczak - GoBDD
GoCracow #5 Bartlomiej klimczak - GoBDDGoCracow #5 Bartlomiej klimczak - GoBDD
GoCracow #5 Bartlomiej klimczak - GoBDD
Bartłomiej Kiełbasa
 
Future vs. Monix Task
Future vs. Monix TaskFuture vs. Monix Task
Future vs. Monix Task
Hermann Hueck
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for Kotlin
TechMagic
 
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018
Meetup di GDG Italia - Leonardo Pirro -  Codemotion Rome 2018 Meetup di GDG Italia - Leonardo Pirro -  Codemotion Rome 2018
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018
Codemotion
 
Kotlin for android developers whats new
Kotlin for android developers whats newKotlin for android developers whats new
Kotlin for android developers whats new
Serghii Chaban
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
Muhammad Abdullah
 
Hello kotlin | An Event by DSC Unideb
Hello kotlin | An Event by DSC UnidebHello kotlin | An Event by DSC Unideb
Hello kotlin | An Event by DSC Unideb
Muhammad Raza
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Languageintelliyole
 
JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)
Anders Jönsson
 
The Ring programming language version 1.7 book - Part 35 of 196
The Ring programming language version 1.7 book - Part 35 of 196The Ring programming language version 1.7 book - Part 35 of 196
The Ring programming language version 1.7 book - Part 35 of 196
Mahmoud Samir Fayed
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
Shaul Rosenzwieg
 
Kotlin @ Devoxx 2011
Kotlin @ Devoxx 2011Kotlin @ Devoxx 2011
Kotlin @ Devoxx 2011
Andrey Breslav
 
Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011Andrey Breslav
 
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
 
Groovy
GroovyGroovy
Groovy
Zen Urban
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
Anıl Sözeri
 

Similar to Kotlin For Android - Functions (part 3 of 7) (20)

What's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritageWhat's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritage
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
 
Kotlin
KotlinKotlin
Kotlin
 
GoCracow #5 Bartlomiej klimczak - GoBDD
GoCracow #5 Bartlomiej klimczak - GoBDDGoCracow #5 Bartlomiej klimczak - GoBDD
GoCracow #5 Bartlomiej klimczak - GoBDD
 
Future vs. Monix Task
Future vs. Monix TaskFuture vs. Monix Task
Future vs. Monix Task
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for Kotlin
 
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018
Meetup di GDG Italia - Leonardo Pirro -  Codemotion Rome 2018 Meetup di GDG Italia - Leonardo Pirro -  Codemotion Rome 2018
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018
 
Kotlin for android developers whats new
Kotlin for android developers whats newKotlin for android developers whats new
Kotlin for android developers whats new
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
 
Hello kotlin | An Event by DSC Unideb
Hello kotlin | An Event by DSC UnidebHello kotlin | An Event by DSC Unideb
Hello kotlin | An Event by DSC Unideb
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Language
 
JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)
 
The Ring programming language version 1.7 book - Part 35 of 196
The Ring programming language version 1.7 book - Part 35 of 196The Ring programming language version 1.7 book - Part 35 of 196
The Ring programming language version 1.7 book - Part 35 of 196
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 
Kotlin @ Devoxx 2011
Kotlin @ Devoxx 2011Kotlin @ Devoxx 2011
Kotlin @ Devoxx 2011
 
Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011
 
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
 
Groovy
GroovyGroovy
Groovy
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
 

More from Gesh Markov

Kotlin For Android - How to Build DSLs (part 7 of 7)
Kotlin For Android - How to Build DSLs (part 7 of 7)Kotlin For Android - How to Build DSLs (part 7 of 7)
Kotlin For Android - How to Build DSLs (part 7 of 7)
Gesh Markov
 
Kotlin For Android - Collections APIs (part 6 of 7)
Kotlin For Android - Collections APIs (part 6 of 7)Kotlin For Android - Collections APIs (part 6 of 7)
Kotlin For Android - Collections APIs (part 6 of 7)
Gesh Markov
 
Kotlin For Android - Useful Kotlin Standard Functions (part 5 of 7)
Kotlin For Android - Useful Kotlin Standard Functions (part 5 of 7)Kotlin For Android - Useful Kotlin Standard Functions (part 5 of 7)
Kotlin For Android - Useful Kotlin Standard Functions (part 5 of 7)
Gesh Markov
 
Kotlin For Android - Properties (part 4 of 7)
Kotlin For Android - Properties (part 4 of 7)Kotlin For Android - Properties (part 4 of 7)
Kotlin For Android - Properties (part 4 of 7)
Gesh Markov
 
Kotlin For Android - Constructors and Control Flow (part 2 of 7)
Kotlin For Android - Constructors and Control Flow (part 2 of 7)Kotlin For Android - Constructors and Control Flow (part 2 of 7)
Kotlin For Android - Constructors and Control Flow (part 2 of 7)
Gesh Markov
 
Kotlin For Android - Basics (part 1 of 7)
Kotlin For Android - Basics (part 1 of 7)Kotlin For Android - Basics (part 1 of 7)
Kotlin For Android - Basics (part 1 of 7)
Gesh Markov
 

More from Gesh Markov (6)

Kotlin For Android - How to Build DSLs (part 7 of 7)
Kotlin For Android - How to Build DSLs (part 7 of 7)Kotlin For Android - How to Build DSLs (part 7 of 7)
Kotlin For Android - How to Build DSLs (part 7 of 7)
 
Kotlin For Android - Collections APIs (part 6 of 7)
Kotlin For Android - Collections APIs (part 6 of 7)Kotlin For Android - Collections APIs (part 6 of 7)
Kotlin For Android - Collections APIs (part 6 of 7)
 
Kotlin For Android - Useful Kotlin Standard Functions (part 5 of 7)
Kotlin For Android - Useful Kotlin Standard Functions (part 5 of 7)Kotlin For Android - Useful Kotlin Standard Functions (part 5 of 7)
Kotlin For Android - Useful Kotlin Standard Functions (part 5 of 7)
 
Kotlin For Android - Properties (part 4 of 7)
Kotlin For Android - Properties (part 4 of 7)Kotlin For Android - Properties (part 4 of 7)
Kotlin For Android - Properties (part 4 of 7)
 
Kotlin For Android - Constructors and Control Flow (part 2 of 7)
Kotlin For Android - Constructors and Control Flow (part 2 of 7)Kotlin For Android - Constructors and Control Flow (part 2 of 7)
Kotlin For Android - Constructors and Control Flow (part 2 of 7)
 
Kotlin For Android - Basics (part 1 of 7)
Kotlin For Android - Basics (part 1 of 7)Kotlin For Android - Basics (part 1 of 7)
Kotlin For Android - Basics (part 1 of 7)
 

Recently uploaded

Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
ayushiqss
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
Peter Caitens
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
MayankTawar1
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
Jelle | Nordend
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
KrzysztofKkol1
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 

Recently uploaded (20)

Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 

Kotlin For Android - Functions (part 3 of 7)

  • 1. Kotlin for Android May 24, 2018 y/kotlin-workbook
  • 2. Functions Operators, Extensions, Inline, Infix, Interop y/kotlin-workbook
  • 3. ● Almost every operator in Kotlin is mapped to a function Operators FUNCTIONS y/kotlin-workbook Expression Translates to a + b a.plus(b) a..b a.rangeTo(b) a in b b.contains(a) a !in b !b.contains(a) a[i] a.get(i) a[i] = b a.set(i, b) a() a.invoke() a(i_1, ..., i_n) a.invoke(i_1, ..., i_n) a += b a.plusAssign(b) a == b a?.equals(b) ?: (b === null) a != b !(a?.equals(b) ?: (b === null)) a > b a.compareTo(b) > 0
  • 4. ● A class can extend from a function Functions Are Types FUNCTIONS y/kotlin-workbook
  • 5. fun world(): String { return "World" } fun world(): String = "World" fun world() = "World"Basic Syntax FUNCTIONS y/kotlin-workbook
  • 6. In depth FUNCTIONS fun world() = "World" object World : () -> String { override fun invoke(): String { return "World" } } y/kotlin-workbook
  • 7. In depth FUNCTIONS fun world() = "World" object World : () -> String { override fun invoke(): String { return "World" } } y/kotlin-workbook
  • 8. In depth FUNCTIONS fun world() = "World" object World : () -> String { override fun invoke() = "World" } fun hello(who: () -> String) { println("Hello ${who()}!") } hello({ "World" }) y/kotlin-workbook
  • 9. In depth FUNCTIONS fun world() = "World" object World : () -> String { override fun invoke() = "World" } fun hello(who: () -> String) { println("Hello ${who()}!") } hello { "World" } y/kotlin-workbook
  • 10. In depth FUNCTIONS fun world() = "World" object World : () -> String { override fun invoke() = "World" } fun hello(who: () -> String) { println("Hello ${who()}!") } hello { "World" } hello(::world) hello(World) y/kotlin-workbook
  • 11. In depth FUNCTIONS fun world() = "World" object World : () -> String { override fun invoke() = "World" } fun hello(who: () -> String) { println("Hello ${who()}!") } hello({ "World" }::invoke::invoke) hello(::world::invoke::invoke::invoke) hello(World::invoke::invoke::invoke::invoke::invoke) y/kotlin-workbook
  • 12. typealias NameProvider = () -> String typealias DeviceName = () -> String fun hello(who: NameProvider, what: DeviceName) { println("Hello ${who()} on ${what()}!") } Functions Are Types typealias FUNCTIONS y/kotlin-workbook
  • 13. Functions Are Types typealias FUNCTIONS typealias NameProvider = () -> String typealias DeviceName = () -> String fun hello(who: NameProvider, what: DeviceName) { println("Hello ${who()} on ${what()}!") } object World : NameProvider { override fun invoke() = "World" } object Device : DeviceName { override fun invoke() = "Android" } y/kotlin-workbook
  • 14. Functions Are Types typealias Warning FUNCTIONS typealias NameProvider = () -> String typealias DeviceName = () -> String fun hello(who: NameProvider, what: DeviceName) { println("Hello ${who()} on ${what()}!") } object World : NameProvider { override fun invoke() = "World" } object Device : DeviceName { override fun invoke() = "Android" } hello(World, Device) // "Hello World on Android!" hello(Device, World) // "Hello Android on World!" hello(what = Device, who = World) y/kotlin-workbook
  • 15. hello(what = Device, who = World) ● You can reorder the arguments you supply when invoking a function if you use their names ● Works only for functions and constructors defined in Kotlin Named Parameters FUNCTIONS y/kotlin-workbook
  • 16. ● Commonly known as extension functions ● Declares receiver type together with its name ● this in the body refers to an instance of the receiver ● Calling from Java the receiver is the first argument Functions with Receivers FUNCTIONS y/kotlin-workbook
  • 17. Functions with Receivers FUNCTIONS // Kotlin fun ViewGroup.foo(): String // Java public static String foo(ViewGroup dis) y/kotlin-workbook
  • 18. Functions with Receivers FUNCTIONS // Kotlin fun ViewGroup.foo(bar: Baz): String // Java public static String foo(ViewGroup dis, Baz bar) y/kotlin-workbook
  • 19. Functions with Receivers FUNCTIONS class Potato { fun ViewGroup.foo(bar: Baz): String { (this is ViewGroup) == true (this@Potato is Potato) == true } } y/kotlin-workbook
  • 20. Functions with Receivers FUNCTIONS val container: ViewGroup = ... container += R.layout.scroll_view y/kotlin-workbook
  • 21. Functions with Receivers FUNCTIONS val container: ViewGroup = ... container += R.layout.scroll_view operator fun ViewGroup.plusAssign( @LayoutRes layout: Int ) { LayoutInflater .from(this.context) .inflate(layout, this, true) } y/kotlin-workbook
  • 22. Higher Order Functions FUNCTIONS fun hi(who: () -> String) = println("Hi ${who()}!") hi { "World" } // prints Hi World! fun hi(who: String, where: () -> String) { println("Hi $who from ${where()}!") } hi("Gesh") { "Hamburg" } // prints Hi Gesh from Hamburg! y/kotlin-workbook ● Improved syntax if the last argument of a function is a function
  • 23. Vararg Functions FUNCTIONS fun main(vararg args: String) // Java public void main(String... args) y/kotlin-workbook ● vararg keyword ● Only one per function ● Usually last unless a higher order function
  • 24. Array Spread Operator FUNCTIONS fun main(vararg args: String) // Java public void main(String... args) val array = arrayOf(1, 2) // [1, 2] val list1 = listOf(array) // [[1, 2]] val list2 = listOf(*array) // [1, 2] val list3 = listOf(0, array, 3) // [0, [1, 2], 3] val list4 = listOf(0, *array, 3) // [0, 1, 2, 3] y/kotlin-workbook ● vararg keyword ● Only one per function ● Usually last unless a higher order function ● Spread an existing array into multiple vararg arguments
  • 25. Infix Functions FUNCTIONS infix fun <A, B> A.to(that: B) = Pair(this, that) mapOf( "a" to "b", "a".to("b"), Pair("a", "b") ) y/kotlin-workbook ● Member or extension functions ● Exactly one argument
  • 26. Inline Functions FUNCTIONS y/kotlin-workbook ● Compiler will inline the body at the call-site ● Cannot be used from Java
  • 27. Inline Functions FUNCTIONS // Java ViewModel model = mock(ViewModel.class) // Kotlin val model: ViewModel = mock(ViewModel::class.java)y/kotlin-workbook ● Compiler will inline the body at the call-site ● Cannot be used from Java ● Can use reified generics
  • 28. Inline Functions FUNCTIONS // Java ViewModel model = mock(ViewModel.class) inline fun <reified T> mock(): T { return Mockito.mock(T::class.java) as T } // Kotlin val model: ViewModel = mock() val model = mock<ViewModel>() y/kotlin-workbook ● Compiler will inline the body at the call-site ● Cannot be used from Java ● Can use reified generics

Editor's Notes

  1. Establish context - this slide is from the previous session Next we’ll go in depth
  2. return type of hello() is Unit Order of operations is a bit strange here
  3. Explain lambdas lambda == annonymous inner final functions Anything that’s true for functions is true for lambdas This makes it easy to write DSLs, which will be in the last presentation
  4. Invoke itself is a type, so it has an invoke keyword Invoke keyword returns the object itself because World is an object of type function
  5. Move last item to next slide
  6. Explain what’s a receiver
  7. Bytecode ends up being exactly the same Kotlin code compiles the former down to the latter
  8. Multiple default receivers if defined inside a class - can use a quialified this@Host to access host member Inner extension functions can only be called from the class in which they are defined Explain closures - all the variables captured in the context of a function
  9. Only arrays can be spread Spreading a list is *list.toArray()
  10. Hit bullet points here
  11. ALMOST END OF SLIDES - NEXT SLIDE IS LAST - Q&A STARTS