File tree 1 file changed +11
-4
lines changed
1 file changed +11
-4
lines changed Original file line number Diff line number Diff line change @@ -21,13 +21,15 @@ Trait ใช้เพื่อแชร์ interface และ field ระห
21
21
22
22
วิธีที่ง่ายที่สุดในการกำหนด trait คือการประกาศด้วย keyword ` trait ` และ indentifier:
23
23
24
- {% tabs trait-hair-color %} {% tab 'Scala 2 and 3' for=trait-hair-color %}
24
+ {% tabs trait-hair-color %}
25
+ {% tab 'Scala 2 and 3' for=trait-hair-color %}
25
26
26
27
``` scala mdoc
27
28
trait HairColor
28
29
```
29
30
30
- {% endtab %} {% endtabs %}
31
+ {% endtab %}
32
+ {% endtabs %}
31
33
32
34
trait จะมีประโยชน์อย่างยิ่งด้วยการเป็น generic type และเป็น abstract method
33
35
@@ -56,9 +58,9 @@ trait Iterator[A]:
56
58
57
59
{% endtabs %}
58
60
59
- การขยาย (extend) ` trait Iterator[A] ` ต้องการ type ` A ` และ implementation ของ method ` hasNext ` และ ` next `
61
+ การขยาย (extend) ` trait Iterator[A] ` ต้องมี implementation ของ method ` hasNext ` และ ` next ` ของ type ` A `
60
62
61
- ## การใช้ Trait
63
+ ## การใช้งาน Trait
62
64
63
65
ใช้ keyword ` extends ` เพื่อขยาย trait จากนั้นให้ implement abstract member ใดๆ ของ trait โดยใช้ keyword ` override ` :
64
66
@@ -198,3 +200,8 @@ animals.foreach(pet => println(pet.name)) // แสดงค่า Harry Sally
198
200
199
201
`trait Pet` มี abstract field `name` ซึ่ง implement ไว้ใน constructor ของคลาส `Cat` และ `Dog`\
200
202
ในบรรทัดสุดท้าย เราเรียกใช้ `pet.name` ซึ่งได้มีการ implement `name` ไว้ใน subtype ใดๆ ของ trait `Pet` แล้ว
203
+
204
+ ## แหล่งข้อมูลเพิ่มเติม
205
+
206
+ * Learn more about traits in the [Scala Book ](/ scala3/ book/ domain- modeling- tools.html# traits)
207
+ * Use traits to define [Enum ](/ scala3/ book/ domain- modeling- fp.html# modeling- the- data)
You can’t perform that action at this time.
0 commit comments