-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path05_Methods.sc
366 lines (320 loc) · 6.98 KB
/
05_Methods.sc
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
// scala
def doSomething(x: Int): String = {
"code here"
}
def plusOne(i: Int) = i + 1
// 5.1 Controlling Method Scope
class Foo {
private[this] def isFoo = true
def doFoo(other: Foo) {
if (other.isFoo) { // this line won't compile
// ...
}
}
}
class Foo {
private def isFoo = true
def doFoo(other: Foo) {
if (other.isFoo) { // this now compiles
// ...
}
}
}
{
class Animal {
private def heartBeat {}
}
class Dog extends Animal {
heartBeat // won't compile
}
}
{
class Animal {
protected def breathe {}
}
class Dog extends Animal {
breathe
}
}
package world
{
class Animal {
protected def breathe {}
}
class Jungle {
val a = new Animal
a.breathe // error: this line won't compile
}
}
package com.acme.coolapp.model
{
class Foo {
private[model] def doX {}
private def doY {}
}
class Bar {
val f = new Foo
f.doX // compiles f.doY // won't compile
}
}
package com.acme.coolapp.model
{
class Foo {
private[model] def doX {}
private[coolapp] def doY {}
private[acme] def doZ {}
}
}
import com.acme.coolapp.model._
package com.acme.coolapp.view
{
class Bar {
val f = new Foo
f.doX // won't compile
f.doY
f.doZ
}
}
package com.acme.common
{
class Bar {
val f = new Foo
f.doX // won't compile
f.doY // won't compile
f.doZ
}
}
package com.acme.coolapp.model
{
class Foo {
def doX {}
}
}
package org.xyz.bar
{
class Bar {
val f = new com.acme.coolapp.model.Foo
f.doX
}
}
// 5.2 Calling a Method on a Superclass
class WelcomeActivity extends Activity {
override def onCreate(bundle: Bundle) {
super.onCreate(bundle)
// more code here ...
}
}
{
class FourLeggedAnimal {
def walk { println("I'm walking") }
def run { println("I'm running") }
}
class Dog extends FourLeggedAnimal {
def walkThenRun {
super.walk
super.run
}
}
val suka = new Dog
suka.walkThenRun
}
{
trait Human { def hello = "the Human trait" }
trait Mother extends Human { override def hello = "Mother" }
trait Father extends Human { override def hello = "Father" }
class Child extends Human with Mother with Father {
def printSuper = super.hello
def printMother = super[Mother].hello
def printFather = super[Father].hello
def printHuman = super[Human].hello
}
object Test extends App {
val c = new Child
println(s"c.printSuper = ${c.printSuper}")
println(s"c.printMother = ${c.printMother}")
println(s"c.printFather = ${c.printFather}")
println(s"c.printHuman = ${c.printHuman}")
}
Test.main(Array())
}
{
trait Animal {
def walk { println("Animal is walking") }
}
class FourLeggedAnimal extends Animal {
override def walk { println("I'm walking on all fours") }
}
class Dog extends FourLeggedAnimal {
def walkThenRun {
super.walk // works
super[FourLeggedAnimal].walk // works
super[Animal].walk // error: won't compile
}
}
}
// 5.3 Setting Default Values for Method Parameters
{
class Connection {
def makeConnection(timeout: Int = 5000, protocol: String = "http") {
println("timeout = %d, protocol = %s".format(timeout, protocol))
// more code here
}
}
val c = new Connection
c.makeConnection()
c.makeConnection(2000)
c.makeConnection(3000, "https")
c.makeConnection(timeout=10000)
c.makeConnection(protocol="https")
c.makeConnection(timeout=10000, protocol="https")
}
// 5.4 Using Parameter Names When Calling a Method
{
class Pizza {
var crustSize = 12
var crustType = "Thin"
def update(crustSize: Int, crustType: String) {
this.crustSize = crustSize
this.crustType = crustType
}
override def toString = {
"A %d inch %s crust pizza.".format(crustSize, crustType)
}
}
val p = new Pizza
p.update(crustSize = 16, crustType = "Thick")
p.update(crustType = "Pan", crustSize = 14)
}
// 5.5 Defining a Method That Returns Multiple Items (Tuples)
{
def getStockInfo = {
// other code here ...
("NFLX", 100.00, 101.00) // this is a Tuple3
}
val (symbol, currentPrice, bidPrice) = getStockInfo
val result = getStockInfo
result._1
result._2
}
// 5.6 Forcing Callers to Leave Parentheses off Accessor Methods
{
class Pizza {
// no parentheses after crustSize
def crustSize = 12
}
val p = new Pizza
p.crustSize
}
// 5.7 Creating Methods That Take Variable-Argument Fields
{
def printAll(strings: String*) {
strings.foreach(println)
}
// these all work
printAll()
printAll("foo")
printAll("foo", "bar")
printAll("foo", "bar", "baz")
}
{
// a sequence of strings
val fruits = List("apple", "banana", "cherry")
// pass the sequence to the varargs field
printAll(fruits: _*)
}
{
def printAll(numbers: Int*) { numbers.foreach(println) }
def printAll(numbers: Int*) { println(numbers.getClass) }
printAll(1, 2, 3)
printAll()
}
// 5.8 Declaring That a Method Can Throw an Exception
@throws(classOf[Exception])
override def play {
// exception throwing code here ...
}
@throws(classOf[IOException])
@throws(classOf[LineUnavailableException])
@throws(classOf[UnsupportedAudioFileException])
def playSoundFileWithJavaAudio {
// exception throwing code here
}
{
object BoomTest extends App {
def boom { throw new Exception }
println("Before boom")
boom
// this line is never reached
println("After boom")
}
BoomTest.main(Array())
}
// 5.9 Supporting a Fluent Style of Programming
{
class Person {
protected var fname = ""
protected var lname = ""
def setFirstName(firstName: String): this.type = {
fname = firstName
this
}
def setLastName(lastName: String): this.type = {
lname = lastName
this
}
}
class Employee extends Person {
protected var role = ""
def setRole(role: String): this.type = {
this.role = role
this
}
override def toString = {
"%s, %s, %s".format(fname, lname, role)
}
}
object Main extends App {
val employee = new Employee
// use the fluent methods
employee
.setFirstName("Al")
.setLastName("Alexander")
.setRole("Developer")
println(employee)
}
Main.main(Array())
}
{
import scala.collection.mutable.ArrayBuffer
final class Pizza {
private val toppings = ArrayBuffer[String]()
private var crustSize = 0
private var crustType = ""
def addTopping(topping: String) = {
toppings += topping
this
}
def setCrustSize(crustSize: Int) = {
this.crustSize = crustSize
this
}
def setCrustType(crustType: String) = {
this.crustType = crustType
this
}
def print() {
println(s"crust size: $crustSize")
println(s"crust type: $crustType")
println(s"toppings: $toppings")
}
}
object FluentPizzaTest extends App {
val p = new Pizza
p.setCrustSize(14)
.setCrustType("thin")
.addTopping("cheese")
.addTopping("green olives")
.print()
}
FluentPizzaTest.main(Array())
}