Skip to content

Commit f0c909c

Browse files
committed
Improve our ability to override default parameters
Don't just use the type of the rhs of the default getter as its inferred type, this can be more precise than the type of the corresponding parameter and prevent seemingly valid overrides.
1 parent 7658237 commit f0c909c

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

compiler/src/dotty/tools/dotc/typer/Namer.scala

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1439,7 +1439,11 @@ class Namer { typer: Typer =>
14391439
val defaultTp = defaultParamType
14401440
val pt = inherited.orElse(wildApprox(defaultTp)).orElse(WildcardType)
14411441
val tp = typedAheadRhs(pt.widenExpr).tpe
1442-
tp.widenTermRefExpr.simplified match
1442+
if (defaultTp eq pt) && (tp frozen_<:< defaultTp) then
1443+
// When possible, widen to the default getter parameter type to permit a
1444+
// larger choice of overrides (see `default-getter.scala`).
1445+
defaultTp
1446+
else tp.widenTermRefExpr.simplified match
14431447
case ctp: ConstantType if isInlineVal => ctp
14441448
case tp =>
14451449
TypeComparer.widenInferred(tp, pt)

tests/pos/default-getter.scala

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
class X
2+
class Y extends X
3+
4+
class A {
5+
def foo(param: X = new Y): X = param
6+
}
7+
8+
class B extends A {
9+
override def foo(param: X = new X): X = param
10+
}

0 commit comments

Comments
 (0)