SlideShare une entreprise Scribd logo
1  sur  38
Télécharger pour lire hors ligne
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!

Contenu connexe

Tendances

Pointcuts and Analysis
Pointcuts and AnalysisPointcuts and Analysis
Pointcuts and Analysis
Wiwat Ruengmee
 
Java concepts and questions
Java concepts and questionsJava concepts and questions
Java concepts and questions
Farag Zakaria
 

Tendances (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
 

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

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
Kurmendra Singh
 
INTRODUCTION TO MATLAB presentation.pptx
INTRODUCTION TO MATLAB presentation.pptxINTRODUCTION TO MATLAB presentation.pptx
INTRODUCTION TO MATLAB presentation.pptx
Devaraj Chilakala
 

Similaire à 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
 

Dernier

%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Dernier (20)

%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 

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