|
| 1 | +# Trait Parameters |
| 2 | + |
| 3 | +Dotty allows traits to have parameters, just like classes have parameters. |
| 4 | + |
| 5 | +```scala |
| 6 | +trait Greeting(val name: String) { |
| 7 | + def msg = s"How are you, $name" |
| 8 | +} |
| 9 | + |
| 10 | +class C extends Greeting("Bob") { |
| 11 | + println(msg) |
| 12 | +} |
| 13 | +``` |
| 14 | + |
| 15 | +Arguments to a trait are evaluated immediately before the trait is initialized. |
| 16 | + |
| 17 | +One potential issue with trait parameters is how to prevent |
| 18 | +ambiguities. For instance, you might try to extend `Greeting` twice, |
| 19 | +with different parameters. |
| 20 | + |
| 21 | +```scala |
| 22 | +/*!*/ class D extends C with Greeting("Bill") // error: parameters passed twice |
| 23 | +``` |
| 24 | + |
| 25 | +Should this print "Bob" or "Bill"? In fact this program is illegal, |
| 26 | +because it violates one of the following rules for trait parameters: |
| 27 | + |
| 28 | + 1. If a class `C` extends a parameterized trait `T`, and its superclass does not, `C` _must_ pass arguments to `T`. |
| 29 | + |
| 30 | + 2. If a class `C` extends a parameterized trait `T`, and its superclass does as well, `C` _may not` pass arguments to `T`. |
| 31 | + |
| 32 | + 3. Traits may never pass arguments to parent traits. |
| 33 | + |
| 34 | +Here's a trait extending the parameterized trait `Greeting`. |
| 35 | + |
| 36 | +```scala |
| 37 | +trait FormalGreeting extends Greeting { |
| 38 | + override def msg = s"How do you do, $name" |
| 39 | +} |
| 40 | +``` |
| 41 | +As is required, no arguments are passed to `Greeting`. However, this poses an issue |
| 42 | +when defining a class that extends `FormalGreeting`: |
| 43 | + |
| 44 | +```scala |
| 45 | +/*!*/ class E extends FormalGreeting // error: missing arguments for `Greeting`. |
| 46 | +``` |
| 47 | + |
| 48 | +The correct way to write `E` is to extend both `Greeting` and |
| 49 | +`FormalGreeting` (in either order): |
| 50 | + |
| 51 | +```scala |
| 52 | +class E extends Greeting("Bob") with FormalGreeting |
| 53 | +``` |
| 54 | + |
| 55 | + |
0 commit comments