Skip to content

Commit fe643f8

Browse files
committed
language tour: improve Traits page
fixes #3097
1 parent 1a0a11e commit fe643f8

File tree

1 file changed

+22
-3
lines changed

1 file changed

+22
-3
lines changed

_tour/traits.md

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,14 @@ prerequisite-knowledge: expressions, classes, generics, objects, companion-objec
1212
redirect_from: "/tutorials/tour/traits.html"
1313
---
1414

15-
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.
1620

1721
## Defining a trait
22+
1823
A minimal trait is simply the keyword `trait` and an identifier:
1924

2025
{% tabs trait-hair-color %}
@@ -130,7 +135,7 @@ val cat = new Cat("Sally")
130135
val animals = ArrayBuffer.empty[Pet]
131136
animals.append(dog)
132137
animals.append(cat)
133-
animals.foreach(pet => println(pet.name)) // Prints Harry Sally
138+
animals.foreach(pet => println(pet.name)) // prints Harry Sally
134139
```
135140
{% endtab %}
136141

@@ -150,14 +155,28 @@ val cat = Cat("Sally")
150155
val animals = ArrayBuffer.empty[Pet]
151156
animals.append(dog)
152157
animals.append(cat)
153-
animals.foreach(pet => println(pet.name)) // Prints Harry Sally
158+
animals.foreach(pet => println(pet.name)) // prints Harry Sally
154159
```
155160
{% endtab %}
156161

157162
{% endtabs %}
158163

159164
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`.
160165

166+
## Trait parameters
167+
168+
In Scala 3, a trait may accept constructor parameters:
169+
170+
{% tabs trait-parameter %}
171+
{% tab 'Scala 3 only' for=trait-parameter %}
172+
```scala mdoc
173+
trait HasLegs(val legCount: Int)
174+
class Spider extends HasLegs(8)
175+
val boris = Spider()
176+
println(boris.legCount) // prints 8
177+
```
178+
{% endtab %}
179+
{% endtabs %}
161180

162181
## More resources
163182

0 commit comments

Comments
 (0)