SlideShare ist ein Scribd-Unternehmen logo
1 von 38
Downloaden Sie, um offline zu lesen
THE WHAT OVER THE HOW
Another way on android development with Kotlin
José Manuel Pereira García (JMPergar)
José Manuel Pereira García
(JMPergar)
Backend Engineer in
jmpergar.com
@jmpergar
jm.pereira.g@gmail.com
Lightweight introduction
to interesting Kotlin features
for functional programming
Support High-Order Functions and Lambda Expressions
In mathematics and computer science, a higher-order function (also
functional, functional form or functor) is a function that does at least one of
the following:
● Takes one or more functions as arguments.
● Returns a function as its result.
● Is assignable to symbols.
fun example() {
val myList: List<Int> = listOf(12, 15, 23, 24, 34, 35, 45)
val myFirstFilteredList = myList.filter({ x -> x > 23 })
val mySecondFilteredList = myList.filter { x -> x > 23 }
val myThirdFilteredList = myList.filter { it > 23 }
val myFilter = getFilterGreaterThan(23)
val myFourthFilteredList = myList.filter(myFilter)
}
private fun getFilter(i: Int): (Int) -> Boolean = { x -> x > i }
private fun getFilterAlternative(i: Int): (Int) -> Boolean = { it > i }
Sealed Classes (As Java Enum but much more powerful)
Sealed classes are used for representing restricted class hierarchies, when a
value can have one of the types from a limited set, but cannot have any other
type.
sealed class Expression {
class Const(val number: Double) : Expression()
class Sum(val e1: Expr, val e2: Expr) : Expression()
object NotANumber : Expression()
}
Sealed Classes (As Java Enum but much more powerful)
The key benefit of using sealed classes comes into play when you use them
in a ‘when expression (as statement)’.
fun eval(expr: Expression): Double = when(expr) {
is Const -> expr.number
is Sum -> eval(expr.e1) + eval(expr.e2)
NotANumber -> Double.NaN
// the 'else' clause is not required because we've covered all the cases
}
Type Inference
In Kotlin, you do not have to specify the type of each variable or return value
explicitly.
// Type is String
val name = "JMPergar"
// Type is Int
var age = 33
// Type is ArrayList
val arrayList = arrayListOf("Kotlin", "Scala")
// Return type is Boolean
private fun getBoolean(x: Int) = x > 12
Exceptions
● All exception classes in Kotlin are descendants of the class Throwable.
● Kotlin does not have checked exceptions.
Lightweight introduction
to Functional Programming
Functional Programming
It’s a programming paradigm that follow this rules:
● Functions are First-class citizen.
● Don’t break referential transparency.
● Avoid mutable data.
"Eliminating side effects can make it much easier to understand
and predict the behavior of a program."
Monads
A Monad is just a monoid in the category of
endofunctors.
What’s the big deal?
Monads
It’s more easy:
● A Monad is a box for a value or set of values of type T1, T2, T3…
● A box with superpowers.
● And this box support two methods:
■ map for transformations.
■ flatMap for sequentiality.
fun <A, B> Monad<A>.map(f: (A) -> B): Monad<B>
val monadStr: Monad<String>
val result: Monad<Int> = monadStr.map { str -> str.length() }
Map method
fun <A, B> Monad<A>.map(f: (A) -> B): Monad<B>
val result1: Monad<String>
val result2: Monad<String>
val result: _________________ =
result1.map {
res1 -> result2.map {
res2 -> res1.length() + res2.length()
}
}
Map method
fun <A, B> Monad<A>.map(f: (A) -> B): Monad<B>
val result1: Monad<String>
val result2: Monad<String>
val result: Monad<Monad<Int>> =
result1.map {
res1 -> result2.map {
res2 -> res1.length() + res2.length()
}
}
Map method
fun <A, B> Monad<A>.flatMap(f: (A) -> Monad<B>): Monad<B>
val result1: Monad<String>
val result2: Monad<String>
val result: __________ =
result1.flatMap {
res1 -> result2.map { res2 -> res1.length() + res2.length() }
}
FlatMap method
fun <A, B> Monad<A>.flatMap(f: (A) -> Monad<B>): Monad<B>
val result1: Monad<String>
val result2: Monad<String>
val result: Monad<Int> =
result1.flatMap {
res1 -> result2.map { res2 -> res1.length() + res2.length() }
}
FlatMap method
Error management with Monads
Old way: Exceptions
● Break referential transparency.
○ Don’t know how to recover from errors (unchecked).
○ Compiler optimization aren’t possible.
○ Break the flow (like GOTO).
● Not valid with asynchrony. Callbacks are needed to move exceptions between
threads.
● Slow (due to fillInStackTrace ) and not constant.
● Checked (info about errors in the signature, but all the other problems persist).
● Boilerplate in the management.
Old way: Callbacks
● Callback Hell
● Boilerplate
New way: Monads
Absence
Option<T> [None] [Some<T>]
Runtime Exceptions
Try<T> [Failure<T>] [Success<T>]
Exceptional cases
Either<L, R> [Left<L>] [Right<R>]
New way: Monads
All types have the same combinators for the
happy case.
Thanks to this and the type inference our
codebase will be much more open to change.
Either<L, R>
Represents a value of one of two possible types (a disjoint union.)
An instance of Either is either an instance of [Left] or [Right].
val myEither: Either<Error, String>
sealed class Errors {
class NetworkError : Error()
class ServerError : Error()
}
With this and methods like map and flatMap we can develop our flow under
the assumption that everything will be ok.
map and flatMap methods
These are our calls with monadic style.
val result1: Either<Error, String> = firstCall()
val result2: Either<Error, String> = secondCall()
val result3: Either<Error, String> = thirdCall()
val result: Either<Error, T> =
result1.flatMap {
str1 -> result2.flatMap {
str2 -> result3.map {
str3 -> str1.length() + str2.length() + str3.length();
}
}
}
But this is still too much verbose. And what about errors?
For Comprehensions
Scala
for {
res1 <- result1
res2 <- result2
res3 <- result3
} yield (res1 + res2 + res3)
Kotlin with Katz
val result = EitherMonad<String>().binding {
val res1 = !result1
val res2 = result2.bind()
val res3 = bind { result3 }
yields(res1 + res2 + res3)
}
Either<Error, String>
Right<Error> Left<String>
Right<Error> Left<Int>
map: (String) -> Int
flatMap: (String) -> Either<Error, Int>
If you need accumulated errors there are other types like ‘Validated’.
Apply side effects
val result = EitherMonad<String>().binding {
val res1 = bind { result1 }
val res2 = bind { result2 }
yields(res1 + res2)
}
processResult(result)
private fun processResult(result: Either<Error, String>): Any? = when (result) {
is Either.Left -> result.swap().map { manageErrors(it) }
is Either.Right -> result.map { manageResult(it) }
}
Other alternatives are use methods like ‘fold’, ‘recover’ (for Try) or similar.
Each implementation has its own methods and are usually based on ‘fold’.
New way (Monads)
And everything is valid
for all monadic types.
Try< String>
Failure<String> Success<String>
Failure<String> Success<Int>
map: (String) -> Int
flatMap: (String) -> Either<Error, Int>
Option<String>
None Option<String>
None Option<Int>
map: (String) -> Int
flatMap: (String) -> Option<Int>
Concurrency management
with Monads
Old way
Promises Libraries
● Clean and semantic but not standard.
RxJava
● Taking a sledgehammer to crack a nut.
● Many not needed features in languages
like kotlin.
● Is your problem reactive?
Java Future
● Java 7: Future (Bloquer).
● Java 8: CompletableFuture (Not
bloquer but not monadic).
Threads
● More difficult to be efficient.
● Easy to have errors.
● Callback hell.
New way: Future<T> (with FutureK)
val myResultFuture: Future<String> =
Future { getResultFromMyServer() }
val myOtherResultFuture: Future<Int> = Future { getOtherFromMyServer() }
val myDataProcessedFuture = myResultFuture.flatMap {
myResult -> myOtherResultFuture.map {
myOtherResult -> processTogether(myResult, myOtherResult)
}
}
myDataProcessedFuture.onComplete {
applySideEffects(it)
}
New way: Future<T> (with Scala)
We can apply ‘for comprehension’ or all monadic combinators too.
val finalResult = for {
res1 <- myResultFuture
res2 <- myOtherResultFuture
} yield (res1 + res2)
finalResult.onComplete {
case Success(result) => processResult(result)
case Failure(t) => println("Error: " + t.getMessage)
}
Conclusions
● Monads provide us a standard way of deal with problems outside our domain.
● Monads abstract and solve standard problems.
● Monads Driven Development make our code more open to change.
Read, analyze, think, but don’t fear the change.
Maybe in the change is the solution.
Links and Resources
● [ESP] Lleva tus use cases al siguiente nivel con Monads y Kotlin
https://jmpergar.com/tech/2017/03/02/lleva-tus-use-cases-al-siguiente-nivel-con-monads.html
● Kotlin Functors, Applicatives, And Monads in Pictures.
https://hackernoon.com/kotlin-functors-applicatives-and-monads-in-pictures-part-1-3-c47a1b1ce25
1
● [ESP] Functional Error Handling https://www.youtube.com/watch?v=cnOA7HdNUR4
● [ESP] Arquitecturas funcionales: más allá de las lambdas https://youtu.be/CT58M6CH0m4
● Antonio Leiva https://antonioleiva.com/category/blog/
● [ESP] DevExperto https://devexperto.com/blog/
● [Book] Kotlin for Android Developers
https://www.amazon.com/Kotlin-Android-Developers-Learn-developing/dp/1530075610
● [Lib] Katz https://github.com/FineCinnamon/Katz
● [Lib] Funktionale https://github.com/MarioAriasC/funKTionale
● [Lib] FutureK https://github.com/JMPergar/FutureK
QUESTIONS & THANKS!

Weitere ähnliche Inhalte

Was ist angesagt?

20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstractionIntro C# Book
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With ScalaKnoldus Inc.
 
Matlab ch1 intro
Matlab ch1 introMatlab ch1 intro
Matlab ch1 introRagu Nathan
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classesIntro C# Book
 
Loops and functions in r
Loops and functions in rLoops and functions in r
Loops and functions in rmanikanta361
 
(chapter 3) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 3) A Concise and Practical Introduction to Programming Algorithms in...(chapter 3) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 3) A Concise and Practical Introduction to Programming Algorithms in...Frank Nielsen
 
Programmation fonctionnelle Scala
Programmation fonctionnelle ScalaProgrammation fonctionnelle Scala
Programmation fonctionnelle ScalaSlim Ouertani
 
Scilab for real dummies j.heikell - part3
Scilab for real dummies j.heikell - part3Scilab for real dummies j.heikell - part3
Scilab for real dummies j.heikell - part3Scilab
 
Java programming lab assignments
Java programming lab assignments Java programming lab assignments
Java programming lab assignments rajni kaushal
 
Pointcuts and Analysis
Pointcuts and AnalysisPointcuts and Analysis
Pointcuts and AnalysisWiwat Ruengmee
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and ClassesIntro C# Book
 
The Ring programming language version 1.3 book - Part 24 of 88
The Ring programming language version 1.3 book - Part 24 of 88The Ring programming language version 1.3 book - Part 24 of 88
The Ring programming language version 1.3 book - Part 24 of 88Mahmoud Samir Fayed
 
Java concepts and questions
Java concepts and questionsJava concepts and questions
Java concepts and questionsFarag Zakaria
 

Was ist angesagt? (20)

Tutorial 2
Tutorial     2Tutorial     2
Tutorial 2
 
Clojure basics
Clojure basicsClojure basics
Clojure basics
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
 
Matlab ch1 intro
Matlab ch1 introMatlab ch1 intro
Matlab ch1 intro
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
 
Monadic Java
Monadic JavaMonadic Java
Monadic Java
 
Loops and functions in r
Loops and functions in rLoops and functions in r
Loops and functions in r
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
 
(chapter 3) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 3) A Concise and Practical Introduction to Programming Algorithms in...(chapter 3) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 3) A Concise and Practical Introduction to Programming Algorithms in...
 
Programmation fonctionnelle Scala
Programmation fonctionnelle ScalaProgrammation fonctionnelle Scala
Programmation fonctionnelle Scala
 
C++ Template
C++ TemplateC++ Template
C++ Template
 
Scilab for real dummies j.heikell - part3
Scilab for real dummies j.heikell - part3Scilab for real dummies j.heikell - part3
Scilab for real dummies j.heikell - part3
 
Introduction to Julia Language
Introduction to Julia LanguageIntroduction to Julia Language
Introduction to Julia Language
 
Java programming lab assignments
Java programming lab assignments Java programming lab assignments
Java programming lab assignments
 
10. Recursion
10. Recursion10. Recursion
10. Recursion
 
Pointcuts and Analysis
Pointcuts and AnalysisPointcuts and Analysis
Pointcuts and Analysis
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
 
The Ring programming language version 1.3 book - Part 24 of 88
The Ring programming language version 1.3 book - Part 24 of 88The Ring programming language version 1.3 book - Part 24 of 88
The Ring programming language version 1.3 book - Part 24 of 88
 
Java concepts and questions
Java concepts and questionsJava concepts and questions
Java concepts and questions
 

Ähnlich wie The what over the how (another way on android development with kotlin)

Idea for ineractive programming language
Idea for ineractive programming languageIdea for ineractive programming language
Idea for ineractive programming languageLincoln Hannah
 
Monadologie
MonadologieMonadologie
Monadologieleague
 
A brief introduction to apply functions
A brief introduction to apply functionsA brief introduction to apply functions
A brief introduction to apply functionsNIKET CHAURASIA
 
Python High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.pptPython High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.pptAnishaJ7
 
Lecture 02: Preliminaries of Data structure
Lecture 02: Preliminaries of Data structureLecture 02: Preliminaries of Data structure
Lecture 02: Preliminaries of Data structureNurjahan Nipa
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++NUST Stuff
 
B61301007 matlab documentation
B61301007 matlab documentationB61301007 matlab documentation
B61301007 matlab documentationManchireddy Reddy
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013amanabr
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Kurmendra Singh
 
Intro to functional programming - Confoo
Intro to functional programming - ConfooIntro to functional programming - Confoo
Intro to functional programming - Confoofelixtrepanier
 
INTRODUCTION TO MATLAB presentation.pptx
INTRODUCTION TO MATLAB presentation.pptxINTRODUCTION TO MATLAB presentation.pptx
INTRODUCTION TO MATLAB presentation.pptxDevaraj Chilakala
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming iiPrashant Kalkar
 
01 - DAA - PPT.pptx
01 - DAA - PPT.pptx01 - DAA - PPT.pptx
01 - DAA - PPT.pptxKokilaK25
 
COMPANION TO MATRICES SESSION II.pptx
COMPANION TO MATRICES SESSION II.pptxCOMPANION TO MATRICES SESSION II.pptx
COMPANION TO MATRICES SESSION II.pptximman gwu
 
Compact and safely: static DSL on Kotlin
Compact and safely: static DSL on KotlinCompact and safely: static DSL on Kotlin
Compact and safely: static DSL on KotlinDmitry Pranchuk
 

Ähnlich wie The what over the how (another way on android development with kotlin) (20)

Idea for ineractive programming language
Idea for ineractive programming languageIdea for ineractive programming language
Idea for ineractive programming language
 
Monadologie
MonadologieMonadologie
Monadologie
 
Learn Matlab
Learn MatlabLearn Matlab
Learn Matlab
 
Matlab1
Matlab1Matlab1
Matlab1
 
A brief introduction to apply functions
A brief introduction to apply functionsA brief introduction to apply functions
A brief introduction to apply functions
 
Python High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.pptPython High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.ppt
 
Lecture 02: Preliminaries of Data structure
Lecture 02: Preliminaries of Data structureLecture 02: Preliminaries of Data structure
Lecture 02: Preliminaries of Data structure
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++
 
B61301007 matlab documentation
B61301007 matlab documentationB61301007 matlab documentation
B61301007 matlab documentation
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
 
Intro to functional programming - Confoo
Intro to functional programming - ConfooIntro to functional programming - Confoo
Intro to functional programming - Confoo
 
Hw09 Hadoop + Clojure
Hw09   Hadoop + ClojureHw09   Hadoop + Clojure
Hw09 Hadoop + Clojure
 
Hadoop + Clojure
Hadoop + ClojureHadoop + Clojure
Hadoop + Clojure
 
EPE821_Lecture3.pptx
EPE821_Lecture3.pptxEPE821_Lecture3.pptx
EPE821_Lecture3.pptx
 
INTRODUCTION TO MATLAB presentation.pptx
INTRODUCTION TO MATLAB presentation.pptxINTRODUCTION TO MATLAB presentation.pptx
INTRODUCTION TO MATLAB presentation.pptx
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
01 - DAA - PPT.pptx
01 - DAA - PPT.pptx01 - DAA - PPT.pptx
01 - DAA - PPT.pptx
 
COMPANION TO MATRICES SESSION II.pptx
COMPANION TO MATRICES SESSION II.pptxCOMPANION TO MATRICES SESSION II.pptx
COMPANION TO MATRICES SESSION II.pptx
 
Compact and safely: static DSL on Kotlin
Compact and safely: static DSL on KotlinCompact and safely: static DSL on Kotlin
Compact and safely: static DSL on Kotlin
 

Kürzlich hochgeladen

Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 

Kürzlich hochgeladen (20)

Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 

The what over the how (another way on android development with kotlin)

  • 1. THE WHAT OVER THE HOW Another way on android development with Kotlin José Manuel Pereira García (JMPergar)
  • 2. José Manuel Pereira García (JMPergar) Backend Engineer in jmpergar.com @jmpergar jm.pereira.g@gmail.com
  • 3. Lightweight introduction to interesting Kotlin features for functional programming
  • 4. Support High-Order Functions and Lambda Expressions In mathematics and computer science, a higher-order function (also functional, functional form or functor) is a function that does at least one of the following: ● Takes one or more functions as arguments. ● Returns a function as its result. ● Is assignable to symbols.
  • 5. fun example() { val myList: List<Int> = listOf(12, 15, 23, 24, 34, 35, 45) val myFirstFilteredList = myList.filter({ x -> x > 23 }) val mySecondFilteredList = myList.filter { x -> x > 23 } val myThirdFilteredList = myList.filter { it > 23 } val myFilter = getFilterGreaterThan(23) val myFourthFilteredList = myList.filter(myFilter) } private fun getFilter(i: Int): (Int) -> Boolean = { x -> x > i } private fun getFilterAlternative(i: Int): (Int) -> Boolean = { it > i }
  • 6. Sealed Classes (As Java Enum but much more powerful) Sealed classes are used for representing restricted class hierarchies, when a value can have one of the types from a limited set, but cannot have any other type. sealed class Expression { class Const(val number: Double) : Expression() class Sum(val e1: Expr, val e2: Expr) : Expression() object NotANumber : Expression() }
  • 7. Sealed Classes (As Java Enum but much more powerful) The key benefit of using sealed classes comes into play when you use them in a ‘when expression (as statement)’. fun eval(expr: Expression): Double = when(expr) { is Const -> expr.number is Sum -> eval(expr.e1) + eval(expr.e2) NotANumber -> Double.NaN // the 'else' clause is not required because we've covered all the cases }
  • 8. Type Inference In Kotlin, you do not have to specify the type of each variable or return value explicitly. // Type is String val name = "JMPergar" // Type is Int var age = 33 // Type is ArrayList val arrayList = arrayListOf("Kotlin", "Scala") // Return type is Boolean private fun getBoolean(x: Int) = x > 12
  • 9. Exceptions ● All exception classes in Kotlin are descendants of the class Throwable. ● Kotlin does not have checked exceptions.
  • 11. Functional Programming It’s a programming paradigm that follow this rules: ● Functions are First-class citizen. ● Don’t break referential transparency. ● Avoid mutable data. "Eliminating side effects can make it much easier to understand and predict the behavior of a program."
  • 12. Monads A Monad is just a monoid in the category of endofunctors. What’s the big deal?
  • 13. Monads It’s more easy: ● A Monad is a box for a value or set of values of type T1, T2, T3… ● A box with superpowers. ● And this box support two methods: ■ map for transformations. ■ flatMap for sequentiality.
  • 14. fun <A, B> Monad<A>.map(f: (A) -> B): Monad<B> val monadStr: Monad<String> val result: Monad<Int> = monadStr.map { str -> str.length() } Map method
  • 15. fun <A, B> Monad<A>.map(f: (A) -> B): Monad<B> val result1: Monad<String> val result2: Monad<String> val result: _________________ = result1.map { res1 -> result2.map { res2 -> res1.length() + res2.length() } } Map method
  • 16. fun <A, B> Monad<A>.map(f: (A) -> B): Monad<B> val result1: Monad<String> val result2: Monad<String> val result: Monad<Monad<Int>> = result1.map { res1 -> result2.map { res2 -> res1.length() + res2.length() } } Map method
  • 17. fun <A, B> Monad<A>.flatMap(f: (A) -> Monad<B>): Monad<B> val result1: Monad<String> val result2: Monad<String> val result: __________ = result1.flatMap { res1 -> result2.map { res2 -> res1.length() + res2.length() } } FlatMap method
  • 18. fun <A, B> Monad<A>.flatMap(f: (A) -> Monad<B>): Monad<B> val result1: Monad<String> val result2: Monad<String> val result: Monad<Int> = result1.flatMap { res1 -> result2.map { res2 -> res1.length() + res2.length() } } FlatMap method
  • 20. Old way: Exceptions ● Break referential transparency. ○ Don’t know how to recover from errors (unchecked). ○ Compiler optimization aren’t possible. ○ Break the flow (like GOTO). ● Not valid with asynchrony. Callbacks are needed to move exceptions between threads. ● Slow (due to fillInStackTrace ) and not constant. ● Checked (info about errors in the signature, but all the other problems persist). ● Boilerplate in the management.
  • 21. Old way: Callbacks ● Callback Hell ● Boilerplate
  • 22. New way: Monads Absence Option<T> [None] [Some<T>] Runtime Exceptions Try<T> [Failure<T>] [Success<T>] Exceptional cases Either<L, R> [Left<L>] [Right<R>]
  • 23. New way: Monads All types have the same combinators for the happy case. Thanks to this and the type inference our codebase will be much more open to change.
  • 24. Either<L, R> Represents a value of one of two possible types (a disjoint union.) An instance of Either is either an instance of [Left] or [Right]. val myEither: Either<Error, String> sealed class Errors { class NetworkError : Error() class ServerError : Error() } With this and methods like map and flatMap we can develop our flow under the assumption that everything will be ok.
  • 25. map and flatMap methods These are our calls with monadic style. val result1: Either<Error, String> = firstCall() val result2: Either<Error, String> = secondCall() val result3: Either<Error, String> = thirdCall() val result: Either<Error, T> = result1.flatMap { str1 -> result2.flatMap { str2 -> result3.map { str3 -> str1.length() + str2.length() + str3.length(); } } } But this is still too much verbose. And what about errors?
  • 26. For Comprehensions Scala for { res1 <- result1 res2 <- result2 res3 <- result3 } yield (res1 + res2 + res3) Kotlin with Katz val result = EitherMonad<String>().binding { val res1 = !result1 val res2 = result2.bind() val res3 = bind { result3 } yields(res1 + res2 + res3) }
  • 27. Either<Error, String> Right<Error> Left<String> Right<Error> Left<Int> map: (String) -> Int flatMap: (String) -> Either<Error, Int> If you need accumulated errors there are other types like ‘Validated’.
  • 28. Apply side effects val result = EitherMonad<String>().binding { val res1 = bind { result1 } val res2 = bind { result2 } yields(res1 + res2) } processResult(result) private fun processResult(result: Either<Error, String>): Any? = when (result) { is Either.Left -> result.swap().map { manageErrors(it) } is Either.Right -> result.map { manageResult(it) } } Other alternatives are use methods like ‘fold’, ‘recover’ (for Try) or similar. Each implementation has its own methods and are usually based on ‘fold’.
  • 29. New way (Monads) And everything is valid for all monadic types.
  • 30. Try< String> Failure<String> Success<String> Failure<String> Success<Int> map: (String) -> Int flatMap: (String) -> Either<Error, Int>
  • 31. Option<String> None Option<String> None Option<Int> map: (String) -> Int flatMap: (String) -> Option<Int>
  • 33. Old way Promises Libraries ● Clean and semantic but not standard. RxJava ● Taking a sledgehammer to crack a nut. ● Many not needed features in languages like kotlin. ● Is your problem reactive? Java Future ● Java 7: Future (Bloquer). ● Java 8: CompletableFuture (Not bloquer but not monadic). Threads ● More difficult to be efficient. ● Easy to have errors. ● Callback hell.
  • 34. New way: Future<T> (with FutureK) val myResultFuture: Future<String> = Future { getResultFromMyServer() } val myOtherResultFuture: Future<Int> = Future { getOtherFromMyServer() } val myDataProcessedFuture = myResultFuture.flatMap { myResult -> myOtherResultFuture.map { myOtherResult -> processTogether(myResult, myOtherResult) } } myDataProcessedFuture.onComplete { applySideEffects(it) }
  • 35. New way: Future<T> (with Scala) We can apply ‘for comprehension’ or all monadic combinators too. val finalResult = for { res1 <- myResultFuture res2 <- myOtherResultFuture } yield (res1 + res2) finalResult.onComplete { case Success(result) => processResult(result) case Failure(t) => println("Error: " + t.getMessage) }
  • 36. Conclusions ● Monads provide us a standard way of deal with problems outside our domain. ● Monads abstract and solve standard problems. ● Monads Driven Development make our code more open to change. Read, analyze, think, but don’t fear the change. Maybe in the change is the solution.
  • 37. Links and Resources ● [ESP] Lleva tus use cases al siguiente nivel con Monads y Kotlin https://jmpergar.com/tech/2017/03/02/lleva-tus-use-cases-al-siguiente-nivel-con-monads.html ● Kotlin Functors, Applicatives, And Monads in Pictures. https://hackernoon.com/kotlin-functors-applicatives-and-monads-in-pictures-part-1-3-c47a1b1ce25 1 ● [ESP] Functional Error Handling https://www.youtube.com/watch?v=cnOA7HdNUR4 ● [ESP] Arquitecturas funcionales: más allá de las lambdas https://youtu.be/CT58M6CH0m4 ● Antonio Leiva https://antonioleiva.com/category/blog/ ● [ESP] DevExperto https://devexperto.com/blog/ ● [Book] Kotlin for Android Developers https://www.amazon.com/Kotlin-Android-Developers-Learn-developing/dp/1530075610 ● [Lib] Katz https://github.com/FineCinnamon/Katz ● [Lib] Funktionale https://github.com/MarioAriasC/funKTionale ● [Lib] FutureK https://github.com/JMPergar/FutureK