|
| 1 | +class Foo[+A] { |
| 2 | + def count(f: A => Boolean = _ => true): Unit = {} |
| 3 | + // The preceding line is valid, even though the generated default getter |
| 4 | + // has type `A => Boolean` which wouldn't normally pass variance checks |
| 5 | + // because it's equivalent to the following overloads which are valid: |
| 6 | + def count2(f: A => Boolean): Unit = {} |
| 7 | + def count2(): Unit = count(_ => true) |
| 8 | +} |
| 9 | + |
| 10 | +class Bar1[+A] extends Foo[A] { |
| 11 | + override def count(f: A => Boolean): Unit = {} |
| 12 | + // This reasoning extends to overrides: |
| 13 | + override def count2(f: A => Boolean): Unit = {} |
| 14 | +} |
| 15 | + |
| 16 | +class Bar2[+A] extends Foo[A] { |
| 17 | + override def count(f: A => Boolean = _ => true): Unit = {} |
| 18 | + // ... including overrides which also override the default getter: |
| 19 | + override def count2(f: A => Boolean): Unit = {} |
| 20 | + override def count2(): Unit = count(_ => true) |
| 21 | +} |
| 22 | + |
| 23 | +// This can be contrasted with the need for variance checks in |
| 24 | +// `protected[this] methods (cf tests/neg/t7093.scala), |
| 25 | +// default getters do not have the same problem since they cannot |
| 26 | +// appear in arbitrary contexts. |
| 27 | + |
| 28 | + |
| 29 | +// Crucially, this argument does not apply to situations in which the default |
| 30 | +// getter result type is not a subtype of the parameter type, for example (from |
| 31 | +// tests/neg/variance.scala): |
| 32 | +// |
| 33 | +// class Foo[+A: ClassTag](x: A) { |
| 34 | +// private[this] val elems: Array[A] = Array(x) |
| 35 | +// def f[B](x: Array[B] = elems): Array[B] = x |
| 36 | +// } |
| 37 | +// |
| 38 | +// If we tried to rewrite this with an overload, it would fail |
| 39 | +// compilation: |
| 40 | +// |
| 41 | +// def f[B](): Array[B] = f(elems) // error: Found: Array[A], Expected: Array[B] |
| 42 | +// |
| 43 | +// So we only disable variance checking for default getters whose |
| 44 | +// result type is the method parameter type, this is checked by |
| 45 | +// `tests/neg/variance.scala` |
0 commit comments