Skip to content

Commit 6638689

Browse files
author
Abel Nieto
committed
Fix #2368: local variables must be initialized
Disallow var declarations initialized to a placholder, if the var declaration is local. `var x: Foo = _` is still allowed in fields. Testing ======= Added tests for both invariants above.
1 parent ff88246 commit 6638689

File tree

4 files changed

+22
-2
lines changed

4 files changed

+22
-2
lines changed

compiler/src/dotty/tools/dotc/reporting/diagnostic/messages.scala

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -490,7 +490,10 @@ object messages {
490490
|${"var a = _"}
491491
|
492492
|Note that this use of `_` is not placeholder syntax,
493-
|but an uninitialized var definition"""
493+
|but an uninitialized var definition.
494+
|Only fields can be left uninitialized in this manner; local variables
495+
|must be initialized.
496+
|"""
494497
}
495498

496499
case class IllegalStartSimpleExpr(illegalToken: String)(implicit ctx: Context)

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

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1175,7 +1175,15 @@ class Typer extends Namer with TypeAssigner with Applications with Implicits wit
11751175
completeAnnotations(vdef, sym)
11761176
val tpt1 = checkSimpleKinded(typedType(tpt))
11771177
val rhs1 = vdef.rhs match {
1178-
case rhs @ Ident(nme.WILDCARD) => rhs withType tpt1.tpe
1178+
case rhs @ Ident(nme.WILDCARD) =>
1179+
// Fields can be left uninitialized, but local variables can't.
1180+
val rhsTyp =
1181+
if (sym.owner.isTerm) {
1182+
errorType(UnboundPlaceholderParameter(), sym.pos)
1183+
} else {
1184+
tpt1.tpe
1185+
}
1186+
rhs withType rhsTyp
11791187
case rhs => typedExpr(rhs, tpt1.tpe)
11801188
}
11811189
val vdef1 = assignType(cpy.ValDef(vdef)(name, tpt1, rhs1), sym)

tests/neg/t2368.scala

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
class C {
2+
def foo() = {
3+
var x: String = _ // error: local variables can't be left uninitialized
4+
}
5+
}

tests/pos/t2368.scala

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
class C {
2+
// A `var` field can be left uninitialized.
3+
var x: String = _
4+
}

0 commit comments

Comments
 (0)