SlideShare ist ein Scribd-Unternehmen logo
1 von 37
Downloaden Sie, um offline zu lesen
Functional Programming
in Kotlin with Arrow
Emmanuel Nhan - 28/06/2018
/me !
• Backend engineer at Sigfox

• Mostly OOP by day (Java, Spring 😒) but FP enthusiast

• FP by night & evangelization at work

• Not FP expert

• @nhanmanu on Twitter
Scope
Functional Programming:
Using pure functions
Strongly typed
Using techniques found in Scala
Kotlin (v1.2.x):
Focus on JVM only
Idioms to build FP
machinery
Arrow (v0.7.2):
How it works
Overview of core
Functional Programming
• Functions, high order functions

• Immutable data

• Referential Transparency

• Abstractions

• Lazy evaluation
Kotlin ?
• Hype 🤩

• Language tasting like Java with lots of sugar 🍯
• Inspired by many existing languages

• Runs on JVM ( including Android), JS, Native

• Developed by Jetbrains

• First class citizen in Android, Spring, Reactor,…
Why FP in Kotlin on JVM ?
• When the team is too scared by Scala

• Idioms which make FP possible & enjoyable

• But concepts are missing : 

need to emulate them
Functions
Functions
// Declaring a simple function
fun add(a: Int, b: Int): Int = a + b
// Or
val minus: (Int, Int) -> Int =
{ a, b -> a - b}
// With generics & high order !
fun <A, B, C> compose(f: (A) ->B,
g: (B) ->C ): (A) ->C =
{ a: A -> g(f(a))}
Function definition
Return typeParameters
Extension Functions
• Feature allowing to add functions to an exiting type

// Enriching Int :
fun Int.minus3(): Int = this - 3
// Works also with generics
fun <A, B, C> ((A, B) ->C).partial(a: A):
(B) ->C = {b: B -> this(a, b)}
• Using this syntax:

6.minus3()
val plus4: (Int) ->Int = ::add.partial(4)
Immutable Data
Structures
Types: data classes
data class Message(val author: String,
val recipient: String,
val content: String)
declares fields which are not reassignable
object
• Allows to declare singletons:

object Bar
• companion object adds methods « to the type itself »

// Declaration
class Foo {
// ...
companion object {
fun bar(): Int = TODO()
}
}
// Use
Foo.bar()
Types: hierarchy
Any
Nothing
Every single type declared in the application
Nothing is called the bottom type : it inherits from all
Types: Option
sealed class Option<out T>
data class Some<out T>(val t: T): Option<T>()
object None: Option<Nothing>()
// Usage:
val a: Option<Int> = Some(4)
val r = when(a){
is Some -> a.t
is None -> 0
}
Not really pattern matching but…
inheritance
Types: recursive structure
sealed class LinkedList<out A>
data class Cons<A>(
val head: A,
val tail: LinkedList<A>
): LinkedList<A>()
object Nil: LinkedList<Nothing>()
Abstractions
Ad-hoc polymorphism
• Technique popularized by Haskell (typeclasses)

• A set of pure functions to fulfill a contract (laws)

• Abstraction over a general property

• No native support in Kotlin (yet)
Order Typeclass
interface Order<T> {
/**
* Compare [x] with [y].
* Returns an Int whose sign is:
* - negative if `x < y`
* - zero if `x = y`
* - positive if `x > y`
*/
fun compare(x: T, y: T): Int
}
Order Typeclass instance
object IntOrderInstance: Order<Int> {
override fun compare(x: Int, y: Int): Int

= when {
x < y -> -1
x > y -> 1
else -> 0
}
}
Usage of Order
/**
* Sort [list] in croissant order.
* Typeclass instance passing by parameter
*/
fun <T> sort(list: List<T>, O: Order<T>):
List<T> = TODO()
Sorting requires a property of ordering
Higher Kinds 101
• Let’s say we have a typeclass SomeTC<F>

• Constraint on F : to be a type shaped like SomeType<A>
• SomeType<A> is a type constructor

with one parameter: A
• Reasoning on theses shapes allows better abstractions
Higher Kind emulation
// Kind definition
interface Kind<out F, out A>
typealias Kind2<F,A,B> = Kind<Kind<F,A>,B>
typealias Kind3<F,A,B,C> = Kind<Kind2<F,A,B>,C>
Type aliasing: makes code more readable
Type constructor parameter
Marker type independent of A
Higher Kind emulation
• Going back to our LinkedList<A>

• Its shape is Kind<F, A>

class ForLinkedList private constructor()
typealias LListOf<A> = Kind<ForLinkedList, A>
sealed class LinkedList<out A>: LListOf<A> { //…
Higher Kinds & Typeclasses
interface Functor<F> {
fun <A, B> map(v: Kind<F, A> ,f: (A) -> B):
Kind<F, B>
}
// Emulation drawback : downcasting…
val l: Kind<ForLinkedList, Int> = //Some call to map()
val fixed: LinkedList<Int> = l.fix()
// Definition of fix()😱 :
fun <A> OptionOf<A>.fix(): Option<A> =
this as Option<A>
Need to downcast !
We can do better
Meet Arrow
• A library based on the principles we just saw

• Inspired by Cats & Scalaz from Scala ecosystem 

• Uses code generation (for now) to reduce boilerplate

• Lots of modules & contributors

• Integrates with other libraries from the Kotlin ecosystem
Arrow typeclasses
• Provides extensions methods :

interface Functor<F> {
fun <A, B> Kind<F, A>.map(f: (A) -> B):
Kind<F, B>
}
• Still no way to avoid fix() . Go vote for KEEP-87 !

• Provides instances for common datatypes

• Uses KAPT to generate boilerplate

• Enhanced syntax
Option
val a: Option<Int> = 3.some()
val b: Option<Int> = 5.some()
val res: Option<Int> = a.flatMap {
x -> b.map { it + x }
}
Option 2
val a: Option<Int> = 3.some()
val b: Option<Int> = 5.some()
val res = ForOption extensions {
binding {
a.bind() + b.bind()
}.fix()
}
Sample: Validation
// THE CONTEXT
import arrow.core.*
import arrow.data.*
typealias AppRawConfig = MapK<String, String>
fun retrieveConf(): AppRawConfig = TODO()
To use Arrow easily
Either & Option
val conf = retrieveConf()
val someParam: Either<String, Int> =
conf.getOption("someParam" ).fold(
{
"Could not find someParam".left()
},{ toParse ->
val nullable: Int? = toParse.toIntOrNull()
nullable.toOption().fold({
"someParam is not an Int".left()
},{
it.right()
})
}
)
Addition from MapK
Extension Method
Kotlin feature
Accumulating failures
• We need a similar structure to Either<L,R> :
Validated<E,A>

• How to accumulate values on the E type ?

• NonEmptyList<A> or Nel<A> makes sure a list contains
at least one element

• We will accumulate in Validated<Nel<String>, T>
ValidatedNel
val otherParam: Either<String, Int> = //TODO()
val someParamV: Validated<String, Int> =
Validated.fromEither(someParam)
val otherParamV: Validated<String, Int> =
Validated.fromEither(otherParam)
val someParamVNel: ValidatedNel<String, Int>
= someParamV.toValidatedNel()
Lifting Either to Validated
Transforming the left type to Nel
Accumulating
data class SomeConfig(val a: Int, val b: Int)
val otherParamVNel: ValidatedNel<String, Int> = // …
val result: ValidatedNel<String, SomeConfig>
= ValidatedNel.applicative(
Nel.semigroup<String>()
)
.map(someParamVNel, otherParamVNel){ t ->
SomeConfig(t.a, t.b)
}.fix()
More Arrow
• Optics

• Recursion schemes

• Integration with Kotlin coroutines, RxJava, Reactor,…

• IO
• Uses much more Kotlin idioms (delegation,…)
Thank you !
Any questions ?
Resources & links
• https://kotlinlang.org/

• https://arrow-kt.io/

• https://gitter.im/arrow-kt/Lobby

• https://typelevel.org/cats/typeclasses.html

• https://www.pacoworks.com/2018/02/25/simple-
dependency-injection-in-kotlin-part-1/

Weitere ähnliche Inhalte

Was ist angesagt?

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 & AnalyticsJohn De Goes
 
Scala-Gopher: CSP-style programming techniques with idiomatic Scala.
Scala-Gopher: CSP-style programming techniques with idiomatic Scala.Scala-Gopher: CSP-style programming techniques with idiomatic Scala.
Scala-Gopher: CSP-style programming techniques with idiomatic Scala.Ruslan Shevchenko
 
TypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason HaffeyTypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason HaffeyRalph Johnson
 
Functor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadFunctor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadOliver Daff
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class PatternsJohn De Goes
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)jeffz
 
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scalafanf42
 
All Aboard The Scala-to-PureScript Express!
All Aboard The Scala-to-PureScript Express!All Aboard The Scala-to-PureScript Express!
All Aboard The Scala-to-PureScript Express!John De Goes
 
Learning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardLearning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardKelsey Gilmore-Innis
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scalapramode_ce
 
1 kotlin vs. java: some java issues addressed in kotlin
1  kotlin vs. java: some java issues addressed in kotlin1  kotlin vs. java: some java issues addressed in kotlin
1 kotlin vs. java: some java issues addressed in kotlinSergey Bandysik
 
stacks and queues class 12 in c++
stacks and  queues class 12 in c++stacks and  queues class 12 in c++
stacks and queues class 12 in c++Khushal Mehta
 
Building a Tagless Final DSL for WebGL
Building a Tagless Final DSL for WebGLBuilding a Tagless Final DSL for WebGL
Building a Tagless Final DSL for WebGLLuka Jacobowitz
 
introduction to c #
introduction to c #introduction to c #
introduction to c #Sireesh K
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in JavaErhan Bagdemir
 

Was ist angesagt? (20)

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
 
Scala-Gopher: CSP-style programming techniques with idiomatic Scala.
Scala-Gopher: CSP-style programming techniques with idiomatic Scala.Scala-Gopher: CSP-style programming techniques with idiomatic Scala.
Scala-Gopher: CSP-style programming techniques with idiomatic Scala.
 
TypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason HaffeyTypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason Haffey
 
Functor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadFunctor, Apply, Applicative And Monad
Functor, Apply, Applicative And Monad
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
 
C++ overview
C++ overviewC++ overview
C++ overview
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)
 
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scala
 
All Aboard The Scala-to-PureScript Express!
All Aboard The Scala-to-PureScript Express!All Aboard The Scala-to-PureScript Express!
All Aboard The Scala-to-PureScript Express!
 
MTL Versus Free
MTL Versus FreeMTL Versus Free
MTL Versus Free
 
Learning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardLearning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a Neckbeard
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
 
Java 8 streams
Java 8 streamsJava 8 streams
Java 8 streams
 
1 kotlin vs. java: some java issues addressed in kotlin
1  kotlin vs. java: some java issues addressed in kotlin1  kotlin vs. java: some java issues addressed in kotlin
1 kotlin vs. java: some java issues addressed in kotlin
 
stacks and queues class 12 in c++
stacks and  queues class 12 in c++stacks and  queues class 12 in c++
stacks and queues class 12 in c++
 
Building a Tagless Final DSL for WebGL
Building a Tagless Final DSL for WebGLBuilding a Tagless Final DSL for WebGL
Building a Tagless Final DSL for WebGL
 
introduction to c #
introduction to c #introduction to c #
introduction to c #
 
2014 java functional
2014 java functional2014 java functional
2014 java functional
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in Java
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 

Ähnlich wie Functional programming in kotlin with Arrow [Sunnytech 2018]

Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, SwiftYandex
 
JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)Eduard Tomàs
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016Codemotion
 
Денис Лебедев, Swift
Денис Лебедев, SwiftДенис Лебедев, Swift
Денис Лебедев, SwiftYandex
 
c++-language-1208539706757125-9.pdf
c++-language-1208539706757125-9.pdfc++-language-1208539706757125-9.pdf
c++-language-1208539706757125-9.pdfnisarmca
 
Functional programming with FSharp
Functional programming with FSharpFunctional programming with FSharp
Functional programming with FSharpDaniele Pozzobon
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard LibrarySantosh Rajan
 
Peyton jones-2009-fun with-type_functions-slide
Peyton jones-2009-fun with-type_functions-slidePeyton jones-2009-fun with-type_functions-slide
Peyton jones-2009-fun with-type_functions-slideTakayuki Muranushi
 
Under the hood of scala implicits (kl10tch 10.03.2015)
Under the hood of scala implicits (kl10tch 10.03.2015)Under the hood of scala implicits (kl10tch 10.03.2015)
Under the hood of scala implicits (kl10tch 10.03.2015)Alexander Podkhalyuzin
 
Power of functions in a typed world
Power of functions in a typed worldPower of functions in a typed world
Power of functions in a typed worldDebasish Ghosh
 
Ch03_stacks_and_queues.ppt
Ch03_stacks_and_queues.pptCh03_stacks_and_queues.ppt
Ch03_stacks_and_queues.pptOliverKane3
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developersJim Roepcke
 
Under the hood of scala implicits (Scala eXchange 2014)
Under the hood of scala implicits (Scala eXchange 2014)Under the hood of scala implicits (Scala eXchange 2014)
Under the hood of scala implicits (Scala eXchange 2014)Alexander Podkhalyuzin
 

Ähnlich wie Functional programming in kotlin with Arrow [Sunnytech 2018] (20)

Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, Swift
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
Developing a new Epsilon EMC driver
Developing a new Epsilon EMC driverDeveloping a new Epsilon EMC driver
Developing a new Epsilon EMC driver
 
JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016
 
Basics of objective c
Basics of objective cBasics of objective c
Basics of objective c
 
Денис Лебедев, Swift
Денис Лебедев, SwiftДенис Лебедев, Swift
Денис Лебедев, Swift
 
Lambdas and Laughs
Lambdas and LaughsLambdas and Laughs
Lambdas and Laughs
 
c++-language-1208539706757125-9.pdf
c++-language-1208539706757125-9.pdfc++-language-1208539706757125-9.pdf
c++-language-1208539706757125-9.pdf
 
Functional programming with FSharp
Functional programming with FSharpFunctional programming with FSharp
Functional programming with FSharp
 
C++.pptx
C++.pptxC++.pptx
C++.pptx
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
 
Angular2 for Beginners
Angular2 for BeginnersAngular2 for Beginners
Angular2 for Beginners
 
Peyton jones-2009-fun with-type_functions-slide
Peyton jones-2009-fun with-type_functions-slidePeyton jones-2009-fun with-type_functions-slide
Peyton jones-2009-fun with-type_functions-slide
 
Functional programming in C++
Functional programming in C++Functional programming in C++
Functional programming in C++
 
Under the hood of scala implicits (kl10tch 10.03.2015)
Under the hood of scala implicits (kl10tch 10.03.2015)Under the hood of scala implicits (kl10tch 10.03.2015)
Under the hood of scala implicits (kl10tch 10.03.2015)
 
Power of functions in a typed world
Power of functions in a typed worldPower of functions in a typed world
Power of functions in a typed world
 
Ch03_stacks_and_queues.ppt
Ch03_stacks_and_queues.pptCh03_stacks_and_queues.ppt
Ch03_stacks_and_queues.ppt
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
 
Under the hood of scala implicits (Scala eXchange 2014)
Under the hood of scala implicits (Scala eXchange 2014)Under the hood of scala implicits (Scala eXchange 2014)
Under the hood of scala implicits (Scala eXchange 2014)
 

Kürzlich hochgeladen

Russian Call Girl South End Park - Call 8250192130 Rs-3500 with A/C Room Cash...
Russian Call Girl South End Park - Call 8250192130 Rs-3500 with A/C Room Cash...Russian Call Girl South End Park - Call 8250192130 Rs-3500 with A/C Room Cash...
Russian Call Girl South End Park - Call 8250192130 Rs-3500 with A/C Room Cash...anamikaraghav4
 
Contact:- 8860008073 Call Girls in Karnal Escort Service Available at Afforda...
Contact:- 8860008073 Call Girls in Karnal Escort Service Available at Afforda...Contact:- 8860008073 Call Girls in Karnal Escort Service Available at Afforda...
Contact:- 8860008073 Call Girls in Karnal Escort Service Available at Afforda...Apsara Of India
 
Karnal Call Girls 8860008073 Dyal Singh Colony Call Girls Service in Karnal E...
Karnal Call Girls 8860008073 Dyal Singh Colony Call Girls Service in Karnal E...Karnal Call Girls 8860008073 Dyal Singh Colony Call Girls Service in Karnal E...
Karnal Call Girls 8860008073 Dyal Singh Colony Call Girls Service in Karnal E...Apsara Of India
 
VIP Call Girls Darjeeling Aaradhya 8250192130 Independent Escort Service Darj...
VIP Call Girls Darjeeling Aaradhya 8250192130 Independent Escort Service Darj...VIP Call Girls Darjeeling Aaradhya 8250192130 Independent Escort Service Darj...
VIP Call Girls Darjeeling Aaradhya 8250192130 Independent Escort Service Darj...Neha Kaur
 
Dakshineswar Call Girls ✔ 8005736733 ✔ Hot Model With Sexy Bhabi Ready For Se...
Dakshineswar Call Girls ✔ 8005736733 ✔ Hot Model With Sexy Bhabi Ready For Se...Dakshineswar Call Girls ✔ 8005736733 ✔ Hot Model With Sexy Bhabi Ready For Se...
Dakshineswar Call Girls ✔ 8005736733 ✔ Hot Model With Sexy Bhabi Ready For Se...aamir
 
Behala ( Call Girls ) Kolkata ✔ 6297143586 ✔ Hot Model With Sexy Bhabi Ready ...
Behala ( Call Girls ) Kolkata ✔ 6297143586 ✔ Hot Model With Sexy Bhabi Ready ...Behala ( Call Girls ) Kolkata ✔ 6297143586 ✔ Hot Model With Sexy Bhabi Ready ...
Behala ( Call Girls ) Kolkata ✔ 6297143586 ✔ Hot Model With Sexy Bhabi Ready ...ritikasharma
 
Call Girls in Barasat | 7001035870 At Low Cost Cash Payment Booking
Call Girls in Barasat | 7001035870 At Low Cost Cash Payment BookingCall Girls in Barasat | 7001035870 At Low Cost Cash Payment Booking
Call Girls in Barasat | 7001035870 At Low Cost Cash Payment Bookingnoor ahmed
 
(KRITI) Pimpri Chinchwad Call Girls Just Call 7001035870 [ Cash on Delivery ]...
(KRITI) Pimpri Chinchwad Call Girls Just Call 7001035870 [ Cash on Delivery ]...(KRITI) Pimpri Chinchwad Call Girls Just Call 7001035870 [ Cash on Delivery ]...
(KRITI) Pimpri Chinchwad Call Girls Just Call 7001035870 [ Cash on Delivery ]...ranjana rawat
 
VIP Call Girls Sonagachi - 8250192130 Escorts Service 50% Off with Cash ON De...
VIP Call Girls Sonagachi - 8250192130 Escorts Service 50% Off with Cash ON De...VIP Call Girls Sonagachi - 8250192130 Escorts Service 50% Off with Cash ON De...
VIP Call Girls Sonagachi - 8250192130 Escorts Service 50% Off with Cash ON De...anamikaraghav4
 
VIP Call Girls in Gulbarga Aarohi 8250192130 Independent Escort Service Gulbarga
VIP Call Girls in Gulbarga Aarohi 8250192130 Independent Escort Service GulbargaVIP Call Girls in Gulbarga Aarohi 8250192130 Independent Escort Service Gulbarga
VIP Call Girls in Gulbarga Aarohi 8250192130 Independent Escort Service GulbargaRiya Pathan
 
↑Top Model (Kolkata) Call Girls Howrah ⟟ 8250192130 ⟟ High Class Call Girl In...
↑Top Model (Kolkata) Call Girls Howrah ⟟ 8250192130 ⟟ High Class Call Girl In...↑Top Model (Kolkata) Call Girls Howrah ⟟ 8250192130 ⟟ High Class Call Girl In...
↑Top Model (Kolkata) Call Girls Howrah ⟟ 8250192130 ⟟ High Class Call Girl In...noor ahmed
 
2k Shot Call girls Laxmi Nagar Delhi 9205541914
2k Shot Call girls Laxmi Nagar Delhi 92055419142k Shot Call girls Laxmi Nagar Delhi 9205541914
2k Shot Call girls Laxmi Nagar Delhi 9205541914Delhi Call girls
 
(Dipika) Call Girls in Bangur ! 8250192130 ₹2999 Only and Free Hotel Delivery...
(Dipika) Call Girls in Bangur ! 8250192130 ₹2999 Only and Free Hotel Delivery...(Dipika) Call Girls in Bangur ! 8250192130 ₹2999 Only and Free Hotel Delivery...
(Dipika) Call Girls in Bangur ! 8250192130 ₹2999 Only and Free Hotel Delivery...Riya Pathan
 
Call Girl Nashik Amaira 7001305949 Independent Escort Service Nashik
Call Girl Nashik Amaira 7001305949 Independent Escort Service NashikCall Girl Nashik Amaira 7001305949 Independent Escort Service Nashik
Call Girl Nashik Amaira 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
VIP Call Girl Kolhapur Aashi 8250192130 Independent Escort Service Kolhapur
VIP Call Girl Kolhapur Aashi 8250192130 Independent Escort Service KolhapurVIP Call Girl Kolhapur Aashi 8250192130 Independent Escort Service Kolhapur
VIP Call Girl Kolhapur Aashi 8250192130 Independent Escort Service KolhapurRiya Pathan
 
Verified Call Girls Esplanade - [ Cash on Delivery ] Contact 8250192130 Escor...
Verified Call Girls Esplanade - [ Cash on Delivery ] Contact 8250192130 Escor...Verified Call Girls Esplanade - [ Cash on Delivery ] Contact 8250192130 Escor...
Verified Call Girls Esplanade - [ Cash on Delivery ] Contact 8250192130 Escor...anamikaraghav4
 
Private Call Girls Durgapur - 8250192130 Escorts Service with Real Photos and...
Private Call Girls Durgapur - 8250192130 Escorts Service with Real Photos and...Private Call Girls Durgapur - 8250192130 Escorts Service with Real Photos and...
Private Call Girls Durgapur - 8250192130 Escorts Service with Real Photos and...Riya Pathan
 
Jinx Manga-Season 1 - Chapters Summary.docx
Jinx Manga-Season 1 - Chapters Summary.docxJinx Manga-Season 1 - Chapters Summary.docx
Jinx Manga-Season 1 - Chapters Summary.docxJinx Manga
 
Call Girls Nashik Gayatri 7001305949 Independent Escort Service Nashik
Call Girls Nashik Gayatri 7001305949 Independent Escort Service NashikCall Girls Nashik Gayatri 7001305949 Independent Escort Service Nashik
Call Girls Nashik Gayatri 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 

Kürzlich hochgeladen (20)

Russian Call Girl South End Park - Call 8250192130 Rs-3500 with A/C Room Cash...
Russian Call Girl South End Park - Call 8250192130 Rs-3500 with A/C Room Cash...Russian Call Girl South End Park - Call 8250192130 Rs-3500 with A/C Room Cash...
Russian Call Girl South End Park - Call 8250192130 Rs-3500 with A/C Room Cash...
 
Contact:- 8860008073 Call Girls in Karnal Escort Service Available at Afforda...
Contact:- 8860008073 Call Girls in Karnal Escort Service Available at Afforda...Contact:- 8860008073 Call Girls in Karnal Escort Service Available at Afforda...
Contact:- 8860008073 Call Girls in Karnal Escort Service Available at Afforda...
 
Karnal Call Girls 8860008073 Dyal Singh Colony Call Girls Service in Karnal E...
Karnal Call Girls 8860008073 Dyal Singh Colony Call Girls Service in Karnal E...Karnal Call Girls 8860008073 Dyal Singh Colony Call Girls Service in Karnal E...
Karnal Call Girls 8860008073 Dyal Singh Colony Call Girls Service in Karnal E...
 
VIP Call Girls Darjeeling Aaradhya 8250192130 Independent Escort Service Darj...
VIP Call Girls Darjeeling Aaradhya 8250192130 Independent Escort Service Darj...VIP Call Girls Darjeeling Aaradhya 8250192130 Independent Escort Service Darj...
VIP Call Girls Darjeeling Aaradhya 8250192130 Independent Escort Service Darj...
 
Dakshineswar Call Girls ✔ 8005736733 ✔ Hot Model With Sexy Bhabi Ready For Se...
Dakshineswar Call Girls ✔ 8005736733 ✔ Hot Model With Sexy Bhabi Ready For Se...Dakshineswar Call Girls ✔ 8005736733 ✔ Hot Model With Sexy Bhabi Ready For Se...
Dakshineswar Call Girls ✔ 8005736733 ✔ Hot Model With Sexy Bhabi Ready For Se...
 
Behala ( Call Girls ) Kolkata ✔ 6297143586 ✔ Hot Model With Sexy Bhabi Ready ...
Behala ( Call Girls ) Kolkata ✔ 6297143586 ✔ Hot Model With Sexy Bhabi Ready ...Behala ( Call Girls ) Kolkata ✔ 6297143586 ✔ Hot Model With Sexy Bhabi Ready ...
Behala ( Call Girls ) Kolkata ✔ 6297143586 ✔ Hot Model With Sexy Bhabi Ready ...
 
Call Girls in Barasat | 7001035870 At Low Cost Cash Payment Booking
Call Girls in Barasat | 7001035870 At Low Cost Cash Payment BookingCall Girls in Barasat | 7001035870 At Low Cost Cash Payment Booking
Call Girls in Barasat | 7001035870 At Low Cost Cash Payment Booking
 
(KRITI) Pimpri Chinchwad Call Girls Just Call 7001035870 [ Cash on Delivery ]...
(KRITI) Pimpri Chinchwad Call Girls Just Call 7001035870 [ Cash on Delivery ]...(KRITI) Pimpri Chinchwad Call Girls Just Call 7001035870 [ Cash on Delivery ]...
(KRITI) Pimpri Chinchwad Call Girls Just Call 7001035870 [ Cash on Delivery ]...
 
VIP Call Girls Sonagachi - 8250192130 Escorts Service 50% Off with Cash ON De...
VIP Call Girls Sonagachi - 8250192130 Escorts Service 50% Off with Cash ON De...VIP Call Girls Sonagachi - 8250192130 Escorts Service 50% Off with Cash ON De...
VIP Call Girls Sonagachi - 8250192130 Escorts Service 50% Off with Cash ON De...
 
VIP Call Girls in Gulbarga Aarohi 8250192130 Independent Escort Service Gulbarga
VIP Call Girls in Gulbarga Aarohi 8250192130 Independent Escort Service GulbargaVIP Call Girls in Gulbarga Aarohi 8250192130 Independent Escort Service Gulbarga
VIP Call Girls in Gulbarga Aarohi 8250192130 Independent Escort Service Gulbarga
 
↑Top Model (Kolkata) Call Girls Howrah ⟟ 8250192130 ⟟ High Class Call Girl In...
↑Top Model (Kolkata) Call Girls Howrah ⟟ 8250192130 ⟟ High Class Call Girl In...↑Top Model (Kolkata) Call Girls Howrah ⟟ 8250192130 ⟟ High Class Call Girl In...
↑Top Model (Kolkata) Call Girls Howrah ⟟ 8250192130 ⟟ High Class Call Girl In...
 
2k Shot Call girls Laxmi Nagar Delhi 9205541914
2k Shot Call girls Laxmi Nagar Delhi 92055419142k Shot Call girls Laxmi Nagar Delhi 9205541914
2k Shot Call girls Laxmi Nagar Delhi 9205541914
 
(Dipika) Call Girls in Bangur ! 8250192130 ₹2999 Only and Free Hotel Delivery...
(Dipika) Call Girls in Bangur ! 8250192130 ₹2999 Only and Free Hotel Delivery...(Dipika) Call Girls in Bangur ! 8250192130 ₹2999 Only and Free Hotel Delivery...
(Dipika) Call Girls in Bangur ! 8250192130 ₹2999 Only and Free Hotel Delivery...
 
Call Girl Nashik Amaira 7001305949 Independent Escort Service Nashik
Call Girl Nashik Amaira 7001305949 Independent Escort Service NashikCall Girl Nashik Amaira 7001305949 Independent Escort Service Nashik
Call Girl Nashik Amaira 7001305949 Independent Escort Service Nashik
 
VIP Call Girl Kolhapur Aashi 8250192130 Independent Escort Service Kolhapur
VIP Call Girl Kolhapur Aashi 8250192130 Independent Escort Service KolhapurVIP Call Girl Kolhapur Aashi 8250192130 Independent Escort Service Kolhapur
VIP Call Girl Kolhapur Aashi 8250192130 Independent Escort Service Kolhapur
 
Verified Call Girls Esplanade - [ Cash on Delivery ] Contact 8250192130 Escor...
Verified Call Girls Esplanade - [ Cash on Delivery ] Contact 8250192130 Escor...Verified Call Girls Esplanade - [ Cash on Delivery ] Contact 8250192130 Escor...
Verified Call Girls Esplanade - [ Cash on Delivery ] Contact 8250192130 Escor...
 
Private Call Girls Durgapur - 8250192130 Escorts Service with Real Photos and...
Private Call Girls Durgapur - 8250192130 Escorts Service with Real Photos and...Private Call Girls Durgapur - 8250192130 Escorts Service with Real Photos and...
Private Call Girls Durgapur - 8250192130 Escorts Service with Real Photos and...
 
Goa Call Girls 9316020077 Call Girls In Goa By Russian Call Girl in goa
Goa Call Girls 9316020077 Call Girls  In Goa By Russian Call Girl in goaGoa Call Girls 9316020077 Call Girls  In Goa By Russian Call Girl in goa
Goa Call Girls 9316020077 Call Girls In Goa By Russian Call Girl in goa
 
Jinx Manga-Season 1 - Chapters Summary.docx
Jinx Manga-Season 1 - Chapters Summary.docxJinx Manga-Season 1 - Chapters Summary.docx
Jinx Manga-Season 1 - Chapters Summary.docx
 
Call Girls Nashik Gayatri 7001305949 Independent Escort Service Nashik
Call Girls Nashik Gayatri 7001305949 Independent Escort Service NashikCall Girls Nashik Gayatri 7001305949 Independent Escort Service Nashik
Call Girls Nashik Gayatri 7001305949 Independent Escort Service Nashik
 

Functional programming in kotlin with Arrow [Sunnytech 2018]

  • 1. Functional Programming in Kotlin with Arrow Emmanuel Nhan - 28/06/2018
  • 2. /me ! • Backend engineer at Sigfox • Mostly OOP by day (Java, Spring 😒) but FP enthusiast • FP by night & evangelization at work • Not FP expert • @nhanmanu on Twitter
  • 3. Scope Functional Programming: Using pure functions Strongly typed Using techniques found in Scala Kotlin (v1.2.x): Focus on JVM only Idioms to build FP machinery Arrow (v0.7.2): How it works Overview of core
  • 4. Functional Programming • Functions, high order functions • Immutable data • Referential Transparency • Abstractions • Lazy evaluation
  • 5. Kotlin ? • Hype 🤩 • Language tasting like Java with lots of sugar 🍯 • Inspired by many existing languages • Runs on JVM ( including Android), JS, Native • Developed by Jetbrains • First class citizen in Android, Spring, Reactor,…
  • 6. Why FP in Kotlin on JVM ? • When the team is too scared by Scala • Idioms which make FP possible & enjoyable • But concepts are missing : 
 need to emulate them
  • 8. Functions // Declaring a simple function fun add(a: Int, b: Int): Int = a + b // Or val minus: (Int, Int) -> Int = { a, b -> a - b} // With generics & high order ! fun <A, B, C> compose(f: (A) ->B, g: (B) ->C ): (A) ->C = { a: A -> g(f(a))} Function definition Return typeParameters
  • 9. Extension Functions • Feature allowing to add functions to an exiting type // Enriching Int : fun Int.minus3(): Int = this - 3 // Works also with generics fun <A, B, C> ((A, B) ->C).partial(a: A): (B) ->C = {b: B -> this(a, b)} • Using this syntax: 6.minus3() val plus4: (Int) ->Int = ::add.partial(4)
  • 11. Types: data classes data class Message(val author: String, val recipient: String, val content: String) declares fields which are not reassignable
  • 12. object • Allows to declare singletons: object Bar • companion object adds methods « to the type itself » // Declaration class Foo { // ... companion object { fun bar(): Int = TODO() } } // Use Foo.bar()
  • 13. Types: hierarchy Any Nothing Every single type declared in the application Nothing is called the bottom type : it inherits from all
  • 14. Types: Option sealed class Option<out T> data class Some<out T>(val t: T): Option<T>() object None: Option<Nothing>() // Usage: val a: Option<Int> = Some(4) val r = when(a){ is Some -> a.t is None -> 0 } Not really pattern matching but… inheritance
  • 15. Types: recursive structure sealed class LinkedList<out A> data class Cons<A>( val head: A, val tail: LinkedList<A> ): LinkedList<A>() object Nil: LinkedList<Nothing>()
  • 17. Ad-hoc polymorphism • Technique popularized by Haskell (typeclasses) • A set of pure functions to fulfill a contract (laws) • Abstraction over a general property • No native support in Kotlin (yet)
  • 18. Order Typeclass interface Order<T> { /** * Compare [x] with [y]. * Returns an Int whose sign is: * - negative if `x < y` * - zero if `x = y` * - positive if `x > y` */ fun compare(x: T, y: T): Int }
  • 19. Order Typeclass instance object IntOrderInstance: Order<Int> { override fun compare(x: Int, y: Int): Int
 = when { x < y -> -1 x > y -> 1 else -> 0 } }
  • 20. Usage of Order /** * Sort [list] in croissant order. * Typeclass instance passing by parameter */ fun <T> sort(list: List<T>, O: Order<T>): List<T> = TODO() Sorting requires a property of ordering
  • 21. Higher Kinds 101 • Let’s say we have a typeclass SomeTC<F> • Constraint on F : to be a type shaped like SomeType<A> • SomeType<A> is a type constructor
 with one parameter: A • Reasoning on theses shapes allows better abstractions
  • 22. Higher Kind emulation // Kind definition interface Kind<out F, out A> typealias Kind2<F,A,B> = Kind<Kind<F,A>,B> typealias Kind3<F,A,B,C> = Kind<Kind2<F,A,B>,C> Type aliasing: makes code more readable Type constructor parameter Marker type independent of A
  • 23. Higher Kind emulation • Going back to our LinkedList<A> • Its shape is Kind<F, A> class ForLinkedList private constructor() typealias LListOf<A> = Kind<ForLinkedList, A> sealed class LinkedList<out A>: LListOf<A> { //…
  • 24. Higher Kinds & Typeclasses interface Functor<F> { fun <A, B> map(v: Kind<F, A> ,f: (A) -> B): Kind<F, B> } // Emulation drawback : downcasting… val l: Kind<ForLinkedList, Int> = //Some call to map() val fixed: LinkedList<Int> = l.fix() // Definition of fix()😱 : fun <A> OptionOf<A>.fix(): Option<A> = this as Option<A> Need to downcast !
  • 25. We can do better
  • 26. Meet Arrow • A library based on the principles we just saw • Inspired by Cats & Scalaz from Scala ecosystem • Uses code generation (for now) to reduce boilerplate • Lots of modules & contributors • Integrates with other libraries from the Kotlin ecosystem
  • 27. Arrow typeclasses • Provides extensions methods : interface Functor<F> { fun <A, B> Kind<F, A>.map(f: (A) -> B): Kind<F, B> } • Still no way to avoid fix() . Go vote for KEEP-87 ! • Provides instances for common datatypes • Uses KAPT to generate boilerplate • Enhanced syntax
  • 28. Option val a: Option<Int> = 3.some() val b: Option<Int> = 5.some() val res: Option<Int> = a.flatMap { x -> b.map { it + x } }
  • 29. Option 2 val a: Option<Int> = 3.some() val b: Option<Int> = 5.some() val res = ForOption extensions { binding { a.bind() + b.bind() }.fix() }
  • 30. Sample: Validation // THE CONTEXT import arrow.core.* import arrow.data.* typealias AppRawConfig = MapK<String, String> fun retrieveConf(): AppRawConfig = TODO() To use Arrow easily
  • 31. Either & Option val conf = retrieveConf() val someParam: Either<String, Int> = conf.getOption("someParam" ).fold( { "Could not find someParam".left() },{ toParse -> val nullable: Int? = toParse.toIntOrNull() nullable.toOption().fold({ "someParam is not an Int".left() },{ it.right() }) } ) Addition from MapK Extension Method Kotlin feature
  • 32. Accumulating failures • We need a similar structure to Either<L,R> : Validated<E,A> • How to accumulate values on the E type ? • NonEmptyList<A> or Nel<A> makes sure a list contains at least one element • We will accumulate in Validated<Nel<String>, T>
  • 33. ValidatedNel val otherParam: Either<String, Int> = //TODO() val someParamV: Validated<String, Int> = Validated.fromEither(someParam) val otherParamV: Validated<String, Int> = Validated.fromEither(otherParam) val someParamVNel: ValidatedNel<String, Int> = someParamV.toValidatedNel() Lifting Either to Validated Transforming the left type to Nel
  • 34. Accumulating data class SomeConfig(val a: Int, val b: Int) val otherParamVNel: ValidatedNel<String, Int> = // … val result: ValidatedNel<String, SomeConfig> = ValidatedNel.applicative( Nel.semigroup<String>() ) .map(someParamVNel, otherParamVNel){ t -> SomeConfig(t.a, t.b) }.fix()
  • 35. More Arrow • Optics • Recursion schemes • Integration with Kotlin coroutines, RxJava, Reactor,… • IO • Uses much more Kotlin idioms (delegation,…)
  • 36. Thank you ! Any questions ?
  • 37. Resources & links • https://kotlinlang.org/ • https://arrow-kt.io/ • https://gitter.im/arrow-kt/Lobby • https://typelevel.org/cats/typeclasses.html • https://www.pacoworks.com/2018/02/25/simple- dependency-injection-in-kotlin-part-1/