File tree 1 file changed +10
-1
lines changed
1 file changed +10
-1
lines changed Original file line number Diff line number Diff line change @@ -15,12 +15,15 @@ Trait ใช้เพื่อแชร์ interface และ field ระห
15
15
คลาส และ object สามารถขยาย trait ได้แต่ trait ไม่สามารถ instant เป็น object และไม่สามารถมี parameter ได้
16
16
17
17
## การกำหนด trait
18
+
18
19
วิธีที่ง่ายที่สุดในการกำหนด trait คือการประกาศด้วย keyword ` trait ` และ indentifier:
19
20
20
21
``` scala mdoc
21
22
trait HairColor
22
23
```
24
+
23
25
trait จะมีประโยชน์อย่างยิ่งด้วยการเป็น generic type และเป็น abstract method
26
+
24
27
``` scala mdoc
25
28
trait Iterator [A ] {
26
29
def hasNext : Boolean
@@ -31,7 +34,9 @@ trait Iterator[A] {
31
34
การขยาย ` trait Iterator[A] ` ต้องการ type ` A ` และ implementation ของ method ` hasNext ` และ ` next `
32
35
33
36
## การใช้ traits
37
+
34
38
ใช้ keyword ` extends ` เพื่อขยาย trait ดังนั้นจะ implement abstract member ใดๆ ของ trait โดยใช้ keyword ` override ` :
39
+
35
40
``` scala mdoc:nest
36
41
trait Iterator [A ] {
37
42
def hasNext : Boolean
@@ -55,10 +60,13 @@ val iterator = new IntIterator(10)
55
60
iterator.next() // returns 0
56
61
iterator.next() // returns 1
57
62
```
63
+
58
64
คลาส ` IntIterator ` นี้รับค่า parameter ` to ` เป็น upper bound มัน ` extends Iterator[Int] ` ซึ่งหมายความว่า method ` next ` จะต้อง return เป็น Int
59
65
60
66
## Subtyping
67
+
61
68
ในเมื่อ trait ที่ให้มานั้น required, subtype ของ trait สามารถถูกใช้แทนที่ได้
69
+
62
70
``` scala mdoc
63
71
import scala .collection .mutable .ArrayBuffer
64
72
@@ -77,5 +85,6 @@ animals.append(dog)
77
85
animals.append(cat)
78
86
animals.foreach(pet => println(pet.name)) // พิมพ์ Harry Sally
79
87
```
80
- ` trait Pet ` มี abstract field ` name ` ซึ่ง implement โดย Cat และ Dog ใน constructor ของมัน
88
+
89
+ ` trait Pet ` มี abstract field ` name ` ซึ่ง implement โดย Cat และ Dog ใน constructor ของมัน
81
90
ในบรรทัดสุดท้าย เราเรียก ` pet.name ` ซึ่งจะต้องถูก implement แล้วใน subtype ใดๆ ของ trait ` Pet `
You can’t perform that action at this time.
0 commit comments