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
animals.foreach(pet => println(pet.name)) // Prints Harry Sally
80
130
```
131
+
{% endtab %}
132
+
133
+
{% tab 'Scala 3' for=trait-pet-example %}
134
+
```scala
135
+
importscala.collection.mutable.ArrayBuffer
136
+
137
+
traitPet:
138
+
valname:String
139
+
140
+
classCat(valname:String) extendsPet
141
+
classDog(valname:String) extendsPet
142
+
143
+
valdog=newDog("Harry")
144
+
valcat=newCat("Sally")
145
+
146
+
valanimals=ArrayBuffer.empty[Pet]
147
+
animals.append(dog)
148
+
animals.append(cat)
149
+
animals.foreach(pet => println(pet.name)) // Prints Harry Sally
150
+
```
151
+
{% endtab %}
152
+
153
+
{% endtabs %}
154
+
81
155
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`.
0 commit comments