scala / bug

Scala 2 bug reports only. Please, no questions — proper bug reports only.
https://scala-lang.org
230 stars 21 forks source link

default value implementation in traits produces NPE #12806

Closed funivan closed 1 year ago

funivan commented 1 year ago

Reproduction steps

  1. create empty project with scala 2.13.10
  2. create file Main.scala with the following content
    
    object Main {
    trait User {
    val name: String
    val formattedName: String = name.capitalize
    }
    case class Admin() extends User{
    override val name = "admin"
    }
    def main(args: Array[String]): Unit = {
    println(
      Admin().formattedName
    )
    }
    }
3. execute `sbt run`

Output:

14:03 ❯ sbt run [info] welcome to sbt 1.8.3 (Azul Systems, Inc. Java 15.0.10) [info] loading global plugins from /Users/ivan/.sbt/1.0/plugins [info] loading project definition from /Users/ivan/src/scala-test-null/project [info] loading settings for project root from build.sbt ... [info] set current project to scala-test-null (in build file:/Users/ivan/src/scala-test-null/) [info] running Main null [success] Total time: 0 s, completed Jun 13, 2023, 2:03:40 PM


## Problem

I expect to have a compilation error. Because there is no way to execute this code correctly.
For example, we might have an error in the line 
`val formattedName: String = name.capitalize` with the suggestion to change `val`  to `def`
som-snytt commented 1 year ago

This is a FAQ https://docs.scala-lang.org/tutorials/FAQ/initialization-order.html

which mentions -Xcheckinit for Scala 2.

Scala 3 has -Ysafe-init:

➜  snips ~/projects/dotty/bin/scalac -Ysafe-init -d /tmp t12806.scala
-- Warning: t12806.scala:8:17 ------------------------------------------------------------------------------------------
8 |    override val name = "admin"
  |                 ^
  |                 Access non-initialized value name. Calling trace:
  |                 -> case class Admin() extends User{ [ t12806.scala:7 ]
  |                    ^
  |                 -> trait User {     [ t12806.scala:3 ]
  |                    ^
  |                 -> val formattedName: String = name.capitalize      [ t12806.scala:5 ]
  |                                                ^^^^
1 warning found