-
Notifications
You must be signed in to change notification settings - Fork 0
/
session5.txt
342 lines (246 loc) · 7.05 KB
/
session5.txt
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
| \b\*Scala Workshop - session 5
1) Organisatorisches
2) Fragen vom letzten mal
3) Futures
4) Promises
5) For-Comprehensions
6) Discuss "homework" (section 3 & 4)
7) Homework for next time
8) Feedback
---
| \b\* Organisatorisches
Es gibt ein ganz brauchbares kostenloses E-Book zum Scala lernen: http://fileadmin.cs.lth.se/scala/scala-impatient.pdf
Da sind bei jedem Kapitel Übungen drinnen Lösungen findet man ggf. im Netz.
+ Themenwünsche sammeln!
---
| \b\* Fragen vom letzten mal
Wer setzt eigentlich Scala ein ... in Deutschland?
https://inoio.de/blog/2014/09/20/technologie-sprung-bei-galeria-kaufhof/
Otto
E-Post
Douglas
--
/
Pattern Matching Talk Scala User Group:
https://github.com/lutzh/pattern-matching-talk
--
/
Pattern matching mit Listen:
```
val numbers = List (2, 4, 6, 8)
def sum(list: List[Int]): Int = {
list match {
case x :: xs => x + sum(xs)
case Nil => 0
}
}
```
---
| \b\* Futures
Scala bietet eine Future Klasse die es erlaubt Aufgaben (z.B. Netzwerk oder Dateizugriffe)
asynchron auszuführen. Vergleichbar mit einem Future bzw. FutureTask in Java.
```
val future = Future {
someBlockingCall()
}
```
--
Dieser Aufruf führt bereits dazu dass das Future einem ExecutionContext zur
Ausführung übergeben wird.
Methodensignatur der apply Methode im Future Companion Objekt:
```
def apply[T](body: =>T)(implicit execctx: ExecutionContext): Future[T]
```
---
Der ExecutionContext kann entweder direkt als Parameter übergeben oder implizit eingebunden
werden. Um die Verwendung von Futures einfacher zu machen, bietet Scala einen globalen
ExecutionContext der automatisch durch einen import verwendet werden kann:
```
import scala.concurrent.ExecutionContext.Implicits.global
val future = Future {
someBlockingCall()
}
```
Syntactic sugar für
```
val future = Future.apply({
someBlockingCall()
})(scala.concurrent.ExecutionContext.Implicits.global)
```
---
| \b\* Beispiel 1
```
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
val f1 = Future {
Thread.sleep(5000)
"Future 1 completed"
}
val f2 = Future {
Thread.sleep(2000)
"Future 2 completed"
}
f1 onSuccess { case str => println(str) }
f2 onSuccess { case str => println(str) }
```
---
| \b\* Beispiel 2
```
import java.lang.RuntimeException
import scala.util.{Try, Success, Failure}
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
val f = Future {
Thread.sleep(2000)
throw new RuntimeException("Future 1 failed")
}
f onComplete {
case Success(str) => println(s"onComplete: $str")
case Failure(t) => println("An error has occured: " + t.getMessage)
}
```
---
| \b\* Verwendung?
Die beiden vorherigen Beispiele haben die onSuccess bzw. onComplete Methoden
des Futures verwendet. Es gibt jedoch weitere Möglichkeiten auf ein Future zu
warten. Dazu gehört die Verwendung von Await
```
import scala.concurrent.Await
import scala.concurrent.duration._
val result = Await.result(future, 10 seconds)
```
Die üblichste ist allerdings die Verwendung der allgegenwärtigen map, flatMap,
filter, ... Funktionen:
```
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
val f1 = Future {
"Future 1 completed"
}
future.map(s => s + " and mapped :)")
```
---
| \b\* Beispiel
Zum Beispiel im Play Framework bei der Verwendung des WSClient um
einen HTTP Aufruf zu tätigen:
```
def scrapeShop() = Action.async {
ws.url("https://shop.rewe.de/").get()
.map(result => processResult(result))
}
```
---
| \b\* Promises
Ein Promise separiert die ausgeführte Berechnung von dem Future. So ist es möglich an einer
beliebigen Stelle im Code bzw. in irgendeinem Thread ein Future zu vervollständigen. Ein Promise
kann dazu genau einmal zugewiesen werden. Verwendet wird es ähnlich dem Producer/Consumer Konzept.
```
import scala.concurrent.{Future, Promise}
import scala.concurrent.ExecutionContext.Implicits.global
val promise = Promise[String]()
val future = promise.future
future onSuccess { case r => println("Promise has been kept: " + r) }
val producer = Future {
val result = "hi there :)"
Thread.sleep(2000)
promise.success(result)
// Do further stuff
}
```
---
| \b\* For-Comprehension
Im ersten Moment ist die For-Comprehension in Scala das äquivalent zur ForEach-Schleife in Java.
```
val countries = List("Australien", "Japan", "Canada")
for (country <- countries) {
println(country)
}
```
--
Will man eine normale for-Schleife mit Zähler nachbauen, kann man in Scala das Range Konstrukt nutzen.
```
for (i <- Range(1, 5)) {
println(i)
}
```
--
Das ganze ist letztlich syntactic sugar für
```
countries.foreach(country => println(country))
Range(1, 5).foreach(i => println(i))
```
---
Es ist auch möglich mehrere solche Ausdrücke zu verschachteln:
```
val countries = List("Australien", "Japan", "Canada")
val relatives = List("mother", "father", "aunt")
for (country <- countries;
relative <- relatives) {
println(s"Sending postcard from $country to $relative")
}
```
--
Ist äquivalent zu
```
countries.foreach(country =>
relatives.foreach(relative =>
println(s"Sending postcard from $country to $relative")))
```
---
| \b\* For-Yield
Der For-Yield Ausdruckt erlaubt es auf jedem Element eine Berechnung auszuführen und
das Ergebnis zurückzugeben:
```
val countries = List("Australien", "Japan", "Canada")
val reversedCountryNames = for (country <- countries) yield country.reverse
```
--
Ist äquivalent zu
```
val reversedCountryNames = countries.map(country => country.reverse)
```
---
Nutzt man nun mehrere 'enums' im Schleifenkopf, wird ein verschachtelter Ausrdruck
mit flatMap und map Operationen generiert. Der Yield-Teil stellt dabei immer den
letzten map() Aufruf da.
# scala -Xshow-phases
# scala -Xprint:parser
```
val lists = List(
List("a1", "a2", "a3"),
List("b1", "b2", "b3"),
List("c1", "c2", "c3")
)
def multiples(a: Int): List[Int] = {
List(a, a*a, a*a*a*a)
}
for (i <- 1 to 5; c <- multiples(i)) yield c
for (i <- 1 to 5; if (i % 2 == 0)) yield i
for (list <- lists; item <- list; smile <- List(item + " :)")) yield smile
```
---
| \b\* Nutzen von For-Yield
Tätigt man mehrere Webservice Aufrufe die voneinander abhängen, z.B.
```
// Webservice substitutes
def getTotallyRandomContinent(): Future[String] = Future { "South America" }
def getCountries(continent: String): Future[List[String]] = Future { List("Brazil", "Colombia", "Argentinia", "Peru", "..." ) }
```
Wollen wir nun beide Webservices verschachtelt aufrufen könnten wir folgendes tun:
```
val continent = getTotallyRandomContinent()
val countries = continent.flatMap(cont => getCountries(cont))
```
--
Alternativ lässt sich dies allerdings auch mit for-yield lösen:
```
for (continent <- getTotallyRandomContinent();
countries <- getCountries(continent)) yield countries
```
Während es in diesem Fall noch nicht zuviel ausmacht. Hilft for-yield hier größere
Verschachtelungen von Aufrufen mit anschließenden flatMap übersichtlich zu halten.
---
| \b\* Homework for next time
Section 5 :)
---
| \b\* Feedback