Skip to content

Widen type of final vars #1285 #1348

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion src/dotty/tools/dotc/typer/Typer.scala
Original file line number Diff line number Diff line change
Expand Up @@ -1008,7 +1008,7 @@ class Typer extends Namer with TypeAssigner with Applications with Implicits wit
def typedValDef(vdef: untpd.ValDef, sym: Symbol)(implicit ctx: Context) = track("typedValDef") {
val ValDef(name, tpt, _) = vdef
completeAnnotations(vdef, sym)
val tpt1 = checkSimpleKinded(typedType(tpt))
val tpt1 = widenIfFinalMutable(checkSimpleKinded(typedType(tpt)), sym)
val rhs1 = vdef.rhs match {
case rhs @ Ident(nme.WILDCARD) => rhs withType tpt1.tpe
case rhs => typedExpr(rhs, tpt1.tpe)
Expand All @@ -1018,6 +1018,16 @@ class Typer extends Namer with TypeAssigner with Applications with Implicits wit
vdef1
}

/** Widen type if a valDef is both mutable and final, see #1285 */
private def widenIfFinalMutable(vdef: Tree, sym: Symbol)(implicit ctx: Context) = {
if (sym.is(allOf(Mutable, Final))) {
val widened = vdef.tpe.widen
vdef.withType(widened)
sym.info_=(widened)
}
vdef
}

/** Add a @volitile to lazy vals when rewriting from Scala2 */
private def patchIfLazy(vdef: ValDef)(implicit ctx: Context): Unit = {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's a simpler way to do it. In Namer.scala

  def isInline = sym.is(Final, butNot = Method)

We just need to exclude Mutable here. E.g.

  def isInline = sym.is(Final, butNot = Method | Mutable)

val sym = vdef.symbol
Expand Down
5 changes: 5 additions & 0 deletions tests/pos/WidenFinalVars.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/* For more information, see #1285 */
class Test {
final var x = false
x = true
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing a new line at the end of the file.