-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathPart4.txt
521 lines (416 loc) · 11.4 KB
/
Part4.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
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
| \*\gScala: The Swiss Army Language
| \cwith Nathan Dotz
https://git.io/oscon16-scala
:bird: \ctwitter: @nathandotz
:octopus: \mgithub: @sleepynate
:sparkling_heart: \yemployer: @DetroitLabs
---
| \*\gPart 4: Objects and Types… finally
---
| \*\gObject oriented programming
| It's finally time to talk about object oriented programming.
---
| \*\gClasses
```
class Foo {
val dingus = "wingle wangle"
def exclaimDingus = dingus + "!"
}
```
--
scala> ```val foo = new Foo```
foo: derp.Foo = derp.Foo@3651d7b4
scala> ```foo.dingus```
res0: String = wingle wangle
scala> ```foo.exclaimDingus```
res1: String = wingle wangle!
---
| \*\gClasses
scala> derp.Foo.dingus
<console>:9: error: object Foo is not a member of package derp
Note: class Foo exists, but it has no companion object.
derp.Foo.dingus
^
scala> derp.Foo.exclaimDingus
<console>:9: error: object Foo is not a member of package derp
Note: class Foo exists, but it has no companion object.
derp.Foo.exclaimDingus
^
---
| \*\gClasses
```
class Foo(val dingus:String) {
def exclaimDingus = dingus + "!"
}
```
scala> ```val foo1 = new Foo("wingle")```
foo1: derp.Foo = derp.Foo@76a11b29
scala> ```val foo2 = new Foo("wangle")```
foo2: derp.Foo = derp.Foo@92260b5
scala> ```foo1.exclaimDingus + " " + foo2.exclaimDingus```
res0: String = wingle! wangle!
---
| \*\gClasses
```
class Foo(val dingus:String, val punc: String, val howExcited:Int) {
def this(dingus:String) = this(dingus, "!", 1)
def this(dingus:String, punc:String) = this(dingus, punc, 1)
def exclaimDingus = dingus + punc * howExcited
}
```
scala> ```val foo = new Foo("yay")```
res0: derp.Foo = derp.Foo@3881bb1
scala> ```foo.exclaimDingus```
res1: String = yay!
scala> ```new Foo("f yea scala!", "?!", 4).exclaimDingus```
res3: String = f yea scala!?!?!?!?!
---
| \*\gCase Classes
scala> ```case class Person(first:String, last:String)```
defined class Person
scala> ```val p1 = new Person("nathan", "dotz")```
res0: Person = Person(nathan,dotz)
scala> ```val p2 = Person("martin", "odersky")```
res1: Person = Person(martin,odersky)
scala> ```p1 == p2```
res3: Boolean = false
scala> ```p2 match {case Person("martin", _)=>println("found a marty!")}```
found a marty!
---
| \*\gObjects
scala> ```object Ooble { def plop(s:String) = "*"+s+"*" }```
defined object Ooble
scala> ```Ooble.plop("boop")```
res0: String = *boop*
scala> ```new Ooble()```
<console>:12: error: not found: type Ooble
new Ooble()
---
| \*\gCompanion Objects
```
class Digboogy(val i: Int, val s: String) {
override def toString = "Digboody("+i+","+s+")"
}
object Digboogy {
private var digboogyCount = 0
def moar = {
digboogyCount = digboogyCount + 1
new Digboogy(digboogyCount, "I number "+digboogyCount)
}
}
```
---
| \*\gCompanion Objects
scala> ```Digboogy.moar```
res4: Digboogy = Digboody(1,I number 1)
scala> ```Digboogy.moar```
res5: Digboogy = Digboody(2,I number 2)
scala> ```Digboogy.moar```
res6: Digboogy = Digboody(3,I number 3)
scala> ```Digboogy.moar```
res7: Digboogy = Digboody(4,I number 4)
scala> ```Digboogy.moar```
res8: Digboogy = Digboody(5,I number 5)
---
| \*\gTraits
scala> ```trait PrintsItself { def print = println(this) }```
defined trait PrintsItself
scala> ```class Foo extends PrintsItself```
defined class Foo
scala> ```val f = new Foo```
f: Foo = Foo@782ed8df
scala> ```f.print```
$line4.$read$$iw$$iw$Foo@782ed8df
---
| \*\gTraits
scala> ```class Bar extends Foo```
defined class Bar
scala> ```val b = new Bar```
b: Bar = Bar@1cad8848
scala> ```b.print```
$line7.$read$$iw$$iw$Bar@1cad8848
scala> ```val o = new Object with PrintsItself```
res7: PrintsItself = $anon$1@2b46950c
scala> ```o.print```
$line15.$read$$iw$$iw$$anon$1@2b46950c
---
| \*\gTypes
Scala's type system is among the most powerful
in mainstream programming languages today.
--
Does your current programming language let you
define a new boolean type?
---
| \*\gTypes
```
sealed abstract trait Bouillon
case object True extends Bouillon
case object False extends Bouillon
def bap(b: Bouillon) = b match {
case True => "You're right!"
case False => "Incorrect"
}
```
scala> ```bap(True)```
res0: String = You're right!
scala> ```bap(False)```
res1: String = Incorrect
---
| \*\gTypes
```
sealed abstract trait Bouillon {
def ==(that: Bouillon): Bouillon
def unary_! : Bouillon
def &&(that: => Bouillon): Bouillon
def ||(that: => Bouillon): Bouillon
}
```
---
| \*\gTypes
```
case object True extends Bouillon {
override def ==(that: Bouillon): Bouillon = that match {
case True => True
case _ => False
}
override def unary_! : Bouillon = False
override def &&(that: => Bouillon): Bouillon = that
override def ||(that: => Bouillon): Bouillon = this
}
```
---
| \*\gTypes
```
case object False extends Bouillon {
override def ==(that: Bouillon): Bouillon = that match {
case False => True
case _ => False
}
override def unary_! : Bouillon = True
override def &&(that: => Bouillon): Bouillon = this
override def ||(that: => Bouillon): Bouillon = that
}
```
---
| \*\gTypes
scala> ```False == True```
res0: Bouillon = True
scala> ```False == !True```
res1: Bouillon = True
scala> ```(!False && !False) || (False || True || True && False)```
res2: Bouillon = True
---
| \*\gParameterized Types
```
object Option {
def apply[A](x: A): Option[A] = if (x == null) None else Some(x)
}
sealed abstract class Option[+A] {
def get: A
}
final case class Some[+A](x: A) extends Option[A] {
def get = x
}
case object None extends Option[Nothing] {
def get = throw new NoSuchElementException("None.get")
}
```
---
| \*\gParameterized Types
scala> ```val x = Option(5)```
x: Option[Int] = Some(5)
scala> ```val y = Option(7)```
y: Option[Int] = Some(7)
scala> ```val n = Option(null)```
n: Option[Null] = None
scala> ```x.get```
res0: Int = 5
scala> ```n.get```
java.util.NoSuchElementException: None.get
---
| \*\gParameterized Types
```
def sumSomes(a: Option[Int], b: Option[Int]) = (a, b) match {
case (Some(x), Some(y)) => x + y
case _ => 0
}
```
scala> ```sumSomes(x, y)```
res4: Int = 12
scala> ```sumSomes(x, n)```
<console>:12: error: type mismatch;
found : Option[Null]
required: Option[Int]
sumSomes(x, n)
^
---
| \*\gWhy define Option?
scala> ```List[Int]().head * 2```
java.util.NoSuchElementException: head of empty list
--
scala> ```List(2).map(_ * 2)```
res1: List[Int] = List(4)
scala> ```List[Int]().map(_ * 2)```
res2: List[Int] = List()
---
| \*\gWhy define Option?
scala> None.map((x:Int) => x * 2)
res5: Option[Int] = None
scala> Option(2).map((x:Int) => x * 2)
res6: Option[Int] = Some(4)
scala> Option(2).map(_ * 2).map(_ + 3).map(_ toString).map(_ + "!!")
res7: Option[String] = Some(7!!!!)
scala> None.map(_ * 2).map(_ + 3).map(_ toString).map(_ + "!!")
res8: Option[String] = None
---
| \*\gCovariance
So what's up with the \c[+A]\s in \csealed abstract class Option[+A]\s?
In Java, \cArrayList<Cat>\s doesn't extend \cArrayList<Animal>\s
\c[+A]\s means "\cA\s or any of its subtypes"
Covariance in \cA\s means \cOption[Cat]\s extends \cOption[Animal]\s
---
| \*\gWhy do we need Covariance?
If we defined \cOption\s like this:
```
sealed abstract class Option[A] {
def get: A
}
```
--
We would get a compile error like this:
Error:(5, 53) type mismatch;
found : None.type
required: Option[A]
Note: Nothing <: A (and None.type <: Option[Nothing]),
but class Option is invariant in type A.
You may wish to define A as +A instead. (SLS 4.5)
def apply[A](x: A): Option[A] = if (x == null) None else Some(x)
^
---
| \*\gRecursive Types
scala> ```1 :: 2 :: 3 :: 4 :: Nil```
res10: List[Int] = List(1, 2, 3, 4)
scala> ```Nil```
res0: scala.collection.immutable.Nil.type = List()
scala> ```4 :: Nil```
res1: List[Int] = List(4)
---
| \*\gRecursive Types
```
sealed trait List[+A]
case object Nil extends List[Nothing]
case class Cons[+A](head: A, tail: List[A]) extends List[A]
```
---
| \*\gRecursive Types
```
sealed trait Lyst[+A] {
def ::[A](that: A) = Cawns(that, this)
}
case object Nihil extends Lyst[Nothing]
case class Cawns[+A](head: A, tail: Lyst[A]) extends Lyst[A]
```
---
| \*\gRecursive Types
scala> ```val l1 = Cawns(5, Nihil)```
l1: Cawns[Int] = Cawns(5,Nihil)
scala> ```val l2 = Cawns(4, l1)```
l2: Cawns[Int] = Cawns(4,Cawns(5,Nihil))
scala> ```val l3 = Cawns(3, l2)```
l3: Cawns[Int] = Cawns(3,Cawns(4,Cawns(5,Nihil)))
--
scala> ```val l4 = 2 :: l3```
l4: Cawns[Any] = Cawns(2,Cawns(3,Cawns(4,Cawns(5,Nihil))))
scala> ```0 :: 1 :: l4```
res4: Cawns[Any] =
Cawns(0,Cawns(1,Cawns(2,Cawns(3,Cawns(4,Cawns(5,Nihil))))))
---
| \*\gType Boundaries
```
sealed trait Lyst[+A] {
def ::[B >: A](that: B):Lyst[B] = Cawns(that, this)
}
case object Nihil extends Lyst[Nothing]
case class Cawns[+A](head: A, tail: Lyst[A]) extends Lyst[A]
```
scala> ```val l5 = "fun" :: Nihil```
l5: Lyst[String] = Cawns(fun,Nihil)
scala> ```val l6 = "scala" :: "is" :: l5```
l6: Lyst[String] = Cawns(scala,Cawns(is,Cawns(fun,Nihil)))
scala> ```val l7 = 5 :: l6```
l7: Lyst[Any] = Cawns(5,Cawns(scala,Cawns(is,Cawns(fun,Nihil))))
---
| \*\gImplicit conversions
\yImplicit conversions\s let us tell Scala that it can
convert between types with the use of functions defined
as \cimplicit\s if it will resolve a type inference.
---
| \*\gImplicit conversions
scala> ```val a: Int = "3719"```
<console>:7: error: type mismatch;
found : String("3719")
required: Int
val a: Int = "3719"
^
--
scala> ```implicit def makeStringsInts(s: String) = s.toInt```
makeStringsInts: (s: String)Int
scala> ```val a: Int = "3719"```
a: Int = 3719
---
| \*\gThe Type Class Pattern
```
trait Mathy[A] {
def add(x: A, y: A): A
def subtract(x: A, y: A): A
def multiply(x: A, y: A): A
def divide(x: A, y: A): A
}
```
We could make a series of classes extend this trait.
However, there's another way to provide implementations
for this trait without introducing any tight coupling
to the classes we want it to operate on.
---
| \*\gThe Type Class Pattern
```
object JustMathyThings {
trait Mathy[A] {
def add(x: A, y: A): A
def subtract(x: A, y: A): A
def multiply(x: A, y: A): A
def divide(x: A, y: A): A
}
implicit object MathyDoubles extends Mathy[Double] {
override def add(x:Double, y:Double):Double = x + y
override def subtract(x:Double, y:Double):Double = add(x, -y)
override def multiply(x:Double, y:Double):Double = x * y
override def divide(x:Double, y:Double):Double = multiply(x, 1 / y)
}
}
```
---
| \*\gThe Type Class Pattern
scala> ```import JustMathyThings.Mathy```
import JustMathyThings.Mathy
scala> ```def doTheAddings[T](x: T, y: T)(implicit m: Mathy[T]) = m.add(x, y)```
doTheAddings: [T](x: T, y: T)(implicit m: mathy.JustMathyThings.Mathy[T])T
scala> ```println(doTheAddings(5.0, 2.0))```
7.0
---
```
implicit object MathyStrings extends Mathy[String] {
override def add(x:String, y:String):String = x + y
override def divide(x:String, y:String):String = x.splitAt(y.length)._1
override def multiply(x:String, y:String):String = x * y.length
override def subtract(x:String, y:String):String = x.splitAt(y.length)._2
}
```
--
scala> ```doTheAddings("five", "two point oh")```
res8: String = fivetwo point oh
---
| \*\gEnd of Part 4!
/ :tulip: :smile: \s
| :relieved: You're all done! Let's eat! :relieved:
/ :hamster: :doughnut: \s