-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path06_Objects.sc
292 lines (242 loc) · 5.93 KB
/
06_Objects.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
// 6.1 Object Casting
{
val a = 10
val b = a.asInstanceOf[Long]
val c = a.asInstanceOf[Byte]
val objects = Array("a", 1)
val arrayOfObject = objects.asInstanceOf[Array[Object]]
val i = 1
// i.asInstanceOf[String]
}
// 6.2 The Scala Equivalent of Java\xe2\x80\x99s .class
val info = new DataLine.Info(classOf[TargetDataLine], null)
// java
// info = new DataLine.Info(TargetDataLine.class, null);
val stringClass = classOf[String]
stringClass.getMethods
// 6.3 Determining the Class of an Object
{
def printAll(numbers: Int*) { println("class: " + numbers.getClass) }
printAll(1, 2, 3)
printAll()
import $ivy.`org.scala-lang.modules::scala-xml:1.2.0`
val hello: scala.xml.Elem = <p>Hello, world</p>
hello.child.foreach(e => println(e.getClass))
val hello: scala.xml.Elem = <p>Hello, <br/>world</p>
hello.child.foreach(e => println(e.getClass))
def printClass(c: Any) { println(c.getClass) }
printClass(1)
printClass("yo")
}
// 6.4 Launching an Application with an Object
{
object Hello extends App {
println("Hello, world")
}
Hello.main(Array())
}
{
object Hello extends App {
if (args.length == 1)
println(s"Hello, ${args(0)}")
else
println("I didn't get your name.")
}
Hello.main(Array("World"))
}
{
object Hello2 {
def main(args: Array[String]) {
println("Hello, world")
}
}
Hello2.main(Array())
}
// 6.5 Creating Singletons with object
{
object CashRegister {
def open { println("opened") }
def close { println("closed") }
}
object Main extends App {
CashRegister.open
CashRegister.close
}
}
{
import java.util.Calendar
import java.text.SimpleDateFormat
object DateUtils {
// as "Thursday, November 29"
def getCurrentDate: String = getCurrentDateTime("EEEE, MMMM d")
// as "6:20 p.m."
def getCurrentTime: String = getCurrentDateTime("K:m aa")
// a common function used by other date/time functions
private def getCurrentDateTime(dateTimeFormat: String): String = {
val dateFormat = new SimpleDateFormat(dateTimeFormat)
val cal = Calendar.getInstance()
dateFormat.format(cal.getTime())
}
}
DateUtils.getCurrentDate
DateUtils.getCurrentTime
}
// 6.6 Creating Static Members with Companion Objects
{
// Pizza class
class Pizza(var crustType: String) {
override def toString = "Crust type is " + crustType
}
// companion object
object Pizza {
val CRUST_TYPE_THIN = "thin"
val CRUST_TYPE_THICK = "thick"
def getFoo = "Foo"
}
println(Pizza.CRUST_TYPE_THIN)
println(Pizza.getFoo)
var p = new Pizza(Pizza.CRUST_TYPE_THICK)
println(p)
}
{
class Foo {
private val secret = 2
}
object Foo {
// access the private class field 'secret'
def double(foo: Foo) = foo.secret * 2
}
object Driver extends App {
val f = new Foo println (Foo.double(f)) // prints 4
}
Driver.main(Array())
}
{
class Foo {
// access the private object field 'obj'
def printObj { println(s"I can see ${Foo.obj}") }
}
object Foo {
private val obj = "Foo's object"
}
object Driver extends App {
val f = new Foo
f.printObj
}
Driver.main(Array())
}
// 6.7 Putting Common Code in Package Objects
package com.alvinalexander.myapp
// com/alvinalexander/myapp/package.scala
package object model {
// field
val MAGIC_NUM = 42
// method
def echo(a: Any) { println(a) }
// enumeration
object Margin extends Enumeration {
type Margin = Value
val TOP, BOTTOM, LEFT, RIGHT = Value
}
// type definition
type MutableMap[K, V] = scala.collection.mutable.Map[K, V]
val MutableMap = scala.collection.mutable.Map
// ---------------------------------------------------------------------------
object MainDriver extends App {
// access our method, constant, and enumeration
echo("Hello, world")
echo(MAGIC_NUM)
echo(Margin.LEFT)
// use our MutableMap type (scala.collection.mutable.Map)
val mm = MutableMap("name" -> "Al")
mm += ("password" -> "123")
for ((k, v) <- mm) printf("key: %s, value: %s\n", k, v)
}
MainDriver.main(Array())
}
// 6.8 Creating Object Instances Without Using the new Keyword
{
class Person {
var name: String = _
}
object Person {
def apply(name: String): Person = {
var p = new Person
p.name = name
p
}
}
val dawn = Person("Dawn")
val a = Array(Person("Dan"), Person("Elijah"))
}
{
case class Person(var name: String)
val p = Person("Fred Flinstone")
val p = Person.apply("Fred Flinstone")
}
{
class Person {
var name = ""
var age = 0
}
object Person {
// a one-arg constructor
def apply(name: String): Person = {
var p = new Person
p.name = name
p
}
// a two-arg constructor
def apply(name: String, age: Int): Person = {
var p = new Person
p.name = name
p.age = age
p
}
}
val fred = Person("Fred")
val john = Person("John", 42)
}
{
// want accessor and mutator methods for the name and age fields
case class Person(var name: String, var age: Int)
// define two auxiliary constructors
object Person {
def apply() = new Person("<no name>", 0)
def apply(name: String) = new Person(name, 0)
}
object Test extends App {
val a = Person()
val b = Person("Al")
val c = Person("William Shatner", 82)
println(a)
println(b)
println(c)
// test the mutator methods
a.name = "Leonard Nimoy"
a.age = 82
println(a)
}
Test.main(Array())
}
// 6.9 Implement the Factory Method in Scala with apply
{
trait Animal {
def speak
}
object Animal {
private class Dog extends Animal {
override def speak { println("woof") }
}
private class Cat extends Animal {
override def speak { println("meow") }
}
// the factory method
def apply(s: String): Animal = {
if (s == "dog") new Dog
else new Cat
}
}
val cat = Animal("cat") // returns a Cat
val dog = Animal("dog") // returns a Dog
}