You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Traits are used to share interfaces and fields between classes. They are similar to Java 8's interfaces. Classes and objects can extend traits, but traits cannot be instantiated and therefore have no parameters.
15
+
Traits are used to represent shared aspects of multiple types. They are similar to Java's interfaces.
16
+
17
+
A trait may contain members which may be abstract or concrete. "Concrete" means the trait includes an implementation for that member.
18
+
19
+
A trait can be extended by classes, objects, and other traits. Extending multiple traits is allowed. A trait may extend a class.
16
20
17
21
## Defining a trait
22
+
18
23
A minimal trait is simply the keyword `trait` and an identifier:
19
24
20
25
{% tabs trait-hair-color %}
@@ -130,7 +135,7 @@ val cat = new Cat("Sally")
130
135
valanimals=ArrayBuffer.empty[Pet]
131
136
animals.append(dog)
132
137
animals.append(cat)
133
-
animals.foreach(pet => println(pet.name)) //Prints Harry Sally
138
+
animals.foreach(pet => println(pet.name)) //prints Harry Sally
134
139
```
135
140
{% endtab %}
136
141
@@ -150,14 +155,28 @@ val cat = Cat("Sally")
150
155
valanimals=ArrayBuffer.empty[Pet]
151
156
animals.append(dog)
152
157
animals.append(cat)
153
-
animals.foreach(pet => println(pet.name)) //Prints Harry Sally
158
+
animals.foreach(pet => println(pet.name)) //prints Harry Sally
154
159
```
155
160
{% endtab %}
156
161
157
162
{% endtabs %}
158
163
159
164
The `trait Pet` has an abstract field `name` that gets implemented by Cat and Dog in their constructors. On the last line, we call `pet.name`, which must be implemented in any subtype of the trait `Pet`.
160
165
166
+
## Trait parameters
167
+
168
+
In Scala 3, a trait may accept constructor parameters:
0 commit comments