-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
1315 lines (986 loc) · 26.4 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<meta charset="utf-8">
<style>
@import url(https://fonts.googleapis.com/css?family=Yanone+Kaffeesatz);
@import url(https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic);
@import url(https://fonts.googleapis.com/css?family=Ubuntu+Mono:400,700,400italic);
body { font-family: 'Droid Serif'; }
h1, h2, h3 {
font-family: 'Yanone Kaffeesatz';
font-weight: normal;
}
.remark-code, .remark-inline-code { font-family: 'Ubuntu Mono'; }
.remark-inline-code {
background-color: #DCDCC6;
padding: .2em .4em;
font-size: 90%;
}
.footnote {
position: absolute;
bottom: 3em;
}
code {
border-radius: 5px;
}
</style>
</head>
<body>
<textarea id="source">
class: center, middle
# Scala for beginners
.footnote[[github.com/vdebergue/scala-beginner](https://github.com/vdebergue/scala-beginner)]
---
# Agenda
1. Introduction
2. Start programming
3. Basics
4. Standard Library
5. ...
---
# Introduction
## Why Scala ?
--
> A problem well put is half solved.
John Dewey
<br>
> A scalable programming language is one in which the same concepts can describe small as well as large parts.
Martin Odersky
---
# In a few words
- Scala is a **general purpose** programming language
- Scala is **object oriented**
- Scala is **statically typed**
- Scala enables both **functional programming** and **imperative programming**
---
class: center, middle
# 2. Start programming
---
# Start programming
## Hello world
```scala
object HelloWorld extends App {
println("Hello world")
}
```
.footnote[`a_hello/A_HelloWorld.scala`]
---
## Running a scala program
- Install [sbt](https://www.scala-sbt.org/)
- Start sbt from root folder of this repo
- Run your main class:
```text
% sbt
sbt:scala-beginner> runMain a_hello.A_HelloWorld
```
_ tab autocompletion works with sbt _
---
## Using the REPL
```text
sbt> console
[info] Starting scala interpreter...
Welcome to Scala 2.12.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_162).
Type in expressions for evaluation. Or try :help.
scala> println("hello !")
hello !
scala> 1+1
res1: Int = 2
```
---
## Scala flexible syntax
```
"The 'Hello world' string" should {
"contain 11 characters" in {
"Hello world" must have size (11)
}
}
```
```
class PingPong extends Actor {
def receive = {
case x => sender ! x
}
}
```
```
class ExprParser extends RegexParsers {
def factor = "[0-9]+".r | "("~expr~")"
def term = factor~("*" | "/")~factor
def expr = term~("+" | "-")~term
}
```
---
class: center, middle
# 3. Basics
---
# Basics
```scala
val x = 32
// x: Int = 32
val y = x + 10
// y: Int = 42
val name = "Scala"
// name: String = "Scala"
var i = 0
// i: Int = 0
i = 1
def lesson = "Values and types"
```
- `val` for value == imutable reference
- `var` for variable == mutable reference
- `def` for definition == evaluated each time it's called
.footnote[_b_basics/A_Values.scala_]
---
# Values and types
Type is infered by the compiler but it can also be supplied
```scala
val x: Int = 32
// x: Int = 32
val name: String = "Scala"
// name: String = "Scala"
def lesson: String = "Types"
def hello(to: String) = println(s"Hello $to !")
```
.footnote[_b_basics/B_Types.scala_]
---
# Common types
Numeric:
- `Int` : 32 bits signed integer
- `Long`: 64 bits signed integer
- `Float` : 32 bits floating point
- `Double`: 64 bits floating point
Other:
- `Boolean`: `true` or `false`
- `String`
---
# Method calls
```scala
"Hello World".size
// res2: Int = 11
```
- Methods are applied on values using the **dot notation**
```scala
1.to(10)
// res3: Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
```
.footnote[_b_basics/C_Methods.scala_]
--
- Infix syntax can be used
```scala
1 to 10
// res4: Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
```
---
# Operators are just methods
```scala
1 + 3 == 1.+(3)
// res5: Boolean = true
"Hello " + "world" == "Hello ".+("world")
// res6: Boolean = true
```
The unification of methods and operators makes the language simplier
.footnote[_b_basics/D_Operators.scala_]
---
# Exercise
- Use the methods `abs` to get the absolute value of `-42`
- Use `toUpperCase` to upper case your name
---
# Types guide you
- Types forbid you to combine values in a wrong way
```scala
1 to "10"
// error: type mismatch;
// found : String("10")
// required: Int
// 1 to "10"
// ^^^^
```
---
# Functions
Functions are expressions that take parameters.
```scala
val addOne = (x: Int) => x + 1
// addOne: Int => Int = <function1>
println(addOne(1))
// 2
```
On the left of `=>` is a list of parameters. On the right is an expression involving the parameters.
Functions may take multiple parameters
```scala
val add = (x: Int, y: Int) => x + y
// add: (Int, Int) => Int = <function2>
println(add(1, 2)) // 3
// 3
```
---
# Methods
```scala
def add(x: Int, y: Int): Int = x + y
// multi parameters list
def addThenMultiply(x: Int, y: Int)(multiplier: Int): Int = (x + y) * multiplier
// no parameters
def name: String = System.getProperty("user.name")
// multiline
def getSquareString(input: Double): String = {
val square = input * input
square.toString
}
```
The last expression of a block is returned.
_Pro Tips:_ Avoid using `return`
---
# Classes
```scala
class Greeter(prefix: String) {
def greet(name: String): Unit = {
println(s"Hello $prefix $name")
}
}
val greeter = new Greeter("little")
// greeter: Greeter = repl.Session$App10$Greeter@31ba9274
greeter.greet("world")
// Hello little world
```
- You use the `class` keyword to define a class.
- A class can be instantiated with the `new` keyword
---
# Case classess
A `case class` is a special class. By default they are immutable
```scala
case class Point(x: Int, y: Int)
val point = Point(10, 10)
// point: Point = Point(10, 10)
val otherPoint = Point(10, 10)
// otherPoint: Point = Point(10, 10)
println(point)
// Point(10,10)
point == otherPoint
// res13: Boolean = true
```
---
# Objects
Objects are single instances of their own definitions. You can think of them as singletons of their own classes.
You can define objects with the object keyword.
```scala
object IdFactory {
private var counter = 0
def create(): Int = {
counter += 1
counter
}
}
```
```scala
val newId: Int = IdFactory.create()
// newId: Int = 1
val newerId: Int = IdFactory.create()
// newerId: Int = 2
```
---
# Traits
```scala
trait WithSize {
def size: Int // abstract method
def isEmpty: Boolean = size == 0 // method with default implementation
}
```
```scala
case class Classroom(nbStudents: Int) extends WithSize {
def size = nbStudents
}
val scalaClassroom = Classroom(32)
// scalaClassroom: Classroom = Classroom(32)
scalaClassroom.isEmpty
// res14: Boolean = false
```
---
# Sealed trait
A sealed trait is a trait where **all sub classes** are defined in the **same file**
```scala
sealed trait SchoolPersonnel { def name: String }
case class Student(name: String) extends SchoolPersonnel
case class Teacher(name: String, subject: String) extends SchoolPersonnel
```
--
Enum example
```scala
sealed trait Weekday
case object Monday extends Weekday
case object Tuesday extends Weekday
case object Wednesday extends Weekday
```
---
# Modeling the world
The combination of `sealed trait` and `case class` gives a convenient way to model information in terms of **is** and **has** relationships
--
- A line is ego-left or ego-right:
- `Line` _sealed trait_ extended by `EgoLeft` and `EgoRight`
- A car has a color and a position
- `Car` _case class_ has `color` and `position` members
--
```scala
sealed trait Line
case object EgoLeft extends Line
case object EgoRight extends Line
case class Car(color: String, position: Vector[Int])
```
---
# Exercise
Model the following domain in Scala:
- A course has a name and a difficulty level
- A difficulty level is either “beginner”, “intermediate” or “advanced”
Can you then define a course named “Programming in Scala” targetting beginners?
---
# Control Flow
```scala
val name = "Scala lessons"
// name: String = "Scala lessons"
val greatness = if (name.contains("Scala")) {
"Awesome"
} else {
"Regular"
}
// greatness: String = "Awesome"
```
```scala
var i = 0
// i: Int = 0
while(i < 10) {
println(s"Count is $i")
i += 1
}
// Count is 0
// Count is 1
// Count is 2
// Count is 3
// Count is 4
// Count is 5
// Count is 6
// Count is 7
// Count is 8
// Count is 9
```
---
# Pattern matching
Syntax:
```scala
val x: Int = scala.util.Random.nextInt(10)
// x: Int = 8
val howMany = x match {
case 0 => "zero"
case 1 => "one"
case 2 => "two"
case _ => "many"
}
// howMany: String = "many"
println(s"Value $x is $howMany")
// Value 8 is many
```
---
# Pattern matching on case class
```scala
sealed trait Shape
case class Rectangle(width: Int, height: Int) extends Shape
case class Triangle(width: Int, height: Int) extends Shape
case class Circle(radius: Int) extends Shape
```
```scala
def showShape(shape: Shape) = shape match {
case Rectangle(w, h) => s"Rectangle of width=$w and height=$h"
case Triangle(w, h) => s"Triangle of width=$w and height=$h"
case Circle(r) => s"Circle of radius=$r"
}
println(showShape(Circle(10)))
// Circle of radius=10
```
---
# Pattern matching
- With guard
```scala
def isSquare(shape: Shape): Boolean = shape match {
case Rectangle(w, h) if w == h => true
case _ => false
}
```
- On type
```scala
def showShape2(shape: Shape) = shape match {
case r: Rectangle => s"Rectangle of width=${r.width} and height=${r.height}"
case t: Triangle => s"Triangle of width=${t.width} and height=${t.height}"
case c: Circle => s"Circle of radius=${c.radius}"
}
showShape2(Triangle(3,10))
// res21: String = "Triangle of width=3 and height=10"
```
_This is the same as `isInstanceOf`_
---
# Exercise
Define a function that takes a course in input and returns a grade:
- if the name of the course contains "Scala" returns a 10
- if the difficulty is low, returns a 8
- if the difficulty is high but the name contains "Python" returns a 9
- else returs a 5
---
class: center, middle
# 4. Standard Library
---
# Option
Used when something can be absent (value was not found, not provided ...)
We can express it using a trait and sealed class (simplified version of the scala lib)
```scala
sealed trait Option[A]
case class Some[A](value: A) extends Option[A]
case object None extends Option[Nothing]
```
Examples:
```scala
Seq.empty[String].headOption
// res23: scala.Option[String] = None
Seq("foo", "bar").headOption
// res24: scala.Option[String] = Some("foo")
Map("foo" -> 1, "bar" -> 2).get("foo")
// res25: scala.Option[Int] = Some(1)
```
---
# Option
How to deal with them ?
--
- Pattern Matching
```scala
val opt = Option(3)
// opt: Option[Int] = Some(3)
opt match {
case Some(x) => s"Got value $x"
case None => "No value :("
}
// res27: String = "Got value 3"
```
--
- Functional construct
```scala
val opt = Option(3)
// opt: Option[Int] = Some(3)
opt.fold("No value :(")(x => s"Got value $x")
// res29: String = "Got value 3"
```
_see also .map, .flatMap, .filter, .getOrElse_
---
# Either
Used to represent a value that can be type `A` or `B`. Mostly used to report errors
Eg.: The return of an api call is an error or a String:
```scala
case class Error(msg: String)
def getResultFromServer(): Either[Error, Int] = ???
```
```scala
val result = getResultFromServer()
// result: Either[Error, Int] = Left(Error("400: Invalid Api call"))
result match {
case Right(x) => s"server result is $x"
case Left(error) => s"Got error when getting result: $error"
}
// res31: String = "Got error when getting result: Error(400: Invalid Api call)"
```
---
# Either
When dealing with errors, by convention the left type represents the error and the right type the value.
Due to that, `Either` is _right-biased_: `.map`, `.filter` functions will apply on the right type
```scala
val doubleResult: Either[Error, Int] = result.map(x => x * 2)
// doubleResult: Either[Error, Int] = Left(Error("400: Invalid Api call"))
val successfulResult: Either[Error, Int] = Right(42)
// successfulResult: Either[Error, Int] = Right(42)
val doubleResult2: Either[Error, Int] = successfulResult.map(x => x * 2)
// doubleResult2: Either[Error, Int] = Right(84)
```
---
# Exercise
- Create a function `makeEasier` that takes a `Course` as input and returns a new course with a lower difficulty level.
If the difficulty is already the lowest, returns a None
- Create a function `makeForNoobs` that takes a `Course` as input and makes it twice easier
---
# Standard Collection
`scala.collection`
.center[]
---
background-image: url(https://docs.scala-lang.org/resources/images/tour/collections-immutable-diagram-213.svg)
# Standard Collection
`scala.collection.immutable`
---
background-image: url(https://docs.scala-lang.org/resources/images/tour/collections-mutable-diagram-213.svg)
background-size: 100%
# Standard Collection
`scala.collection.mutable`
---
# Standard Collection Overview
```scala
import scala.collection._
Iterable("x", "y", "z")
Map("x" -> 24, "y" -> 25, "z" -> 26)
Set(Color.red, Color.green, Color.blue)
SortedSet("hello", "world")
mutable.Buffer('x', 'y', 'z')
IndexedSeq(1.0, 2.0)
LinearSeq('a', 'b', 'c')
// Specific implems
List(1, 2, 3)
mutable.TreeMap("x" -> 24, "y" -> 25, "z" -> 26)
```
---
# Seq, List, Vector
```scala
val xs = Seq(1, 2, 3)
// xs: Seq[Int] = List(1, 2, 3)
xs(0)
// res42: Int = 1
// xs(10) // throws Exception
xs.length // 3
// res43: Int = 3 // 3
xs.map(x => x + 1)
// res44: Seq[Int] = List(2, 3, 4)
xs.filter(x => x > 1)
// res45: Seq[Int] = List(2, 3)
val (evens, ods) = xs.partition(x => x % 2 == 0)
// evens: Seq[Int] = List(2)
// ods: Seq[Int] = List(1, 3)
val a = List(1, 2, 3)
// a: List[Int] = List(1, 2, 3)
val b = Vector(1, 2, 3)
// b: Vector[Int] = Vector(1, 2, 3)
a == b
// res46: Boolean = true
```
---
# Map
```scala
val capitals = Map(
"France" -> "Paris",
"USA" -> "Washington",
"China" -> "Beijing"
)
// capitals: Map[String, String] = Map(
// "France" -> "Paris",
// "USA" -> "Washington",
// "China" -> "Beijing"
// )
capitals("France")
// res47: String = "Paris"
capitals.get("France")
// res48: Option[String] = Some("Paris")
capitals.get("Argentina")
// res49: Option[String] = None
capitals.getOrElse("Argentina", "Unknown")
// res50: String = "Unknown"
val updated = capitals ++ Map("Argentina" -> "Buenos Aires")
// updated: Map[String, String] = Map(
// "France" -> "Paris",
// "USA" -> "Washington",
// "China" -> "Beijing",
// "Argentina" -> "Buenos Aires"
// )
```
---
# Set
```scala
val colors = Set("red", "green", "blue")
// colors: Set[String] = Set("red", "green", "blue")
colors.contains("red")
// res51: Boolean = true
colors.contains("white")
// res52: Boolean = false
colors intersect Set("red", "white")
// res53: Set[String] = Set("red")
colors union Set("red", "white")
// res54: Set[String] = Set("red", "green", "blue", "white")
colors diff Set("red", "white")
// res55: Set[String] = Set("green", "blue")
```
---
# Exercise
Create a class `CourseCatalog` that contains a catalog of `Course`. On this `CourseCatalog` a user should be able to:
- `listByDifficulty(difficulty)`: get the list of `Course` according to a difficulty
- `search(query)`: get the list of `Course` where the name contains the user query
- `getNames`: get the names of all the courses
- `getStats`: returns the number of course by difficulty: `beginner -> 3, intermediate -> 2, advanced -> 4`
---
# For comprehension
```scala
case class Image(width: Int, height: Int)
case class Pixel(x: Int, y: Int)
val image: Image = Image(16,16)
// image: Image = Image(16, 16)
```
How get a list of all pixels of an image ?
---
# For comprehension
```scala
val pixels: Seq[Pixel] = (0 until image.width).flatMap { x =>
(0 until image.height).map { y =>
Pixel(x, y)
}
}
```
--
This can be rewritten as
```scala
val pixels2 = for {
x <- 0 until image.width
y <- 0 until image.height
} yield Pixel(x, y)
```
```scala
pixels == pixels2
// res56: Boolean = true
```
---
# For comprehension
for comprehension are just syntatic sugar. The compiler will translate them to `.map` `.flatMap`
They work on all types that define a `.map` `flatMap`
```scala
def getServerResult(): Either[Error, Int] = ???
def runCalculation(input: Int): Either[Error, Calculation] = ???
def storeCalculation(calc: Calculation): Either[Error, Id] = ???
def storageId: Either[Error, Id] = for {
result <- getServerResult()
calculation <- runCalculation(result)
id <- storeCalculation(calculation)
} yield id
```
---
# Future
- Futures provide a way to reason about performing many operations in parallel– in an efficient and non-blocking way
- A Future is a placeholder object for a value that may not yet exist
- Composing concurrent tasks in this way tends to result in faster, asynchronous, non-blocking parallel code.
```scala
import scala.concurrent.{ExecutionContext, Future}
implicit val ec: ExecutionContext = ExecutionContext.global
def runExpensiveCalculation(): Long = ??? // non-blocking long lasting computation
val resultFuture : Future[Long] = Future {
runExpensiveCalculation()
} // ec is implicitly passed
```
--
```scala
// equivalent to
val resultFuture2: Future[Long] = Future {
runExpensiveCalculation() // non-blocking long lasting computation
}(ec)
```
--
The code delegates the execution of `runExpensiveCalculation()` to an `ExecutionContext` and embody the result of the computation in `resultFuture`
---
# Future
A `Future` is an object holding a value which may become available at some point. This value is usually the result of some other computation:
- If the computation has not yet completed, we say that the `Future` is **not completed**.
- If the computation has completed with a value or with an exception, we say that the `Future` is **completed**.
--
Completion can take one of two forms:
- When a `Future` is completed with a value, we say that the `Future` was **successfully** completed with that value.
- When a `Future` is completed with an exception thrown by the computation, we say that the `Future` was **failed** with that exception.
--
A `Future` has an important property that it may only be assigned once
Once a Future object is given a value or an exception, it becomes in effect **immutable**
---
# Future
```scala
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
println("Starting...")
val myValue = Future {
Thread.sleep(1000)
println("Computed my value")
2 + 2
}
println("Creating double result")
val doubleValue = myValue.map(_ * 2)
doubleValue.foreach{ result =>
println(s"My result is $result")
}
println("Done or not ?")
```
What does the console stdout looks like ?
---
# Future
Let's make a cake !
```scala
val chocolate: Chocolate = Chocolate(black=0.80)
val eggs: List[Egg] = List.fill(3)(Egg)
val flour: Flour = Flour.White
// Functions alreay provided for us
def shopForMilk(): Future[Milk] = ...
def prepareCakeDough(milk: Milk, eggs: Seq[Egg], flour: Flour): Future[CakeDough] = ...
def cookCake(chocolate: Chocolate, dough: CakeDough): Future[Cake] = ...
// My cooking:
val cake: Future[Cake] = ???
```
---
# Future
Let's make a cake !
```scala
val chocolate: Chocolate = Chocolate(black=0.80)
val eggs: List[Egg] = List.fill(3)(Egg)
val flour: Flour = Flour.White
// Functions alreay provided for us
def shopForMilk(): Future[Milk] = ...
def prepareCakeDough(milk: Milk, eggs: Seq[Egg], flour: Flour): Future[CakeDough] = ...
def cookCake(chocolate: Chocolate, dough: CakeDough): Future[Cake] = ...
// My cooking:
val cake: Future[Cake] = shopForMilk.flatMap { milk =>
prepareCakeDough(milk, eggs, flour).flatMap { dough =>
cookCake(chocolate, dough)
}
}
```
---
# Future