Skip to content

Commit ab0171a

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

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

_tour/traits.md

Lines changed: 18 additions & 1 deletion
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 and to what some languages call "mixins".
16+
17+
A trait may contain member `def`s, `val`s, and `var`s, 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 %}
@@ -158,6 +163,18 @@ animals.foreach(pet => println(pet.name)) // Prints Harry Sally
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' for=trait-parameter %}
172+
```scala mdoc
173+
trait HasLegs(legCount: Int)
174+
class Spider extends HasLegs(8)
175+
```
176+
{% endtab %}
177+
{% endtabs %}
161178

162179
## More resources
163180

0 commit comments

Comments
 (0)