scala / bug

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

Circular dependencies through fields in ADT result in null values #12700

Closed helgi98 closed 1 year ago

helgi98 commented 1 year ago

Reproduction steps

Scala version: 2.3.8

sealed abstract class RPS(val score: Int, val beats: RPS)

case object Rock extends RPS(1, Scissors)

case object Paper extends RPS(2, Rock)

case object Scissors extends RPS(3, Paper)

println(Rock.beats) // prints Scissors
println(Paper.beats) // prints null
println(Scissors.beats) // prints Paper

Problem

Paper.beats should be evaluated to Rock and not null. When you evaluate only Paper.beats it works just fine, but if all three are printed then it produces null.

som-snytt commented 1 year ago

Someone just posted an issue about initialization of circular dependencies. I don't know if this is a "normal" modelling concern or exacerbated by the season of puzzling.

Consider the local case:

object X {
  sealed abstract class RPS(val score: Int, val beats: RPS)

  case object Rock extends RPS(1, Scissors)

  case object Paper extends RPS(2, Rock)

  case object Scissors extends RPS(3, Paper)
}

object Test extends App {
  import X._
  println(Rock.beats) // prints Scissors
  println(Paper.beats) // prints null
  println(Scissors.beats) // prints Paper
  def f: Unit = {
    sealed abstract class RPS(val score: Int, val beats: RPS)
    case object Rock extends RPS(1, Scissors)
    case object Paper extends RPS(2, Rock)
    case object Scissors extends RPS(3, Paper)
    println(Rock.beats) // prints Scissors
    println(Paper.beats) // prints null
    println(Scissors.beats) // prints Paper
  }
  f
}

This issue and links from there: https://github.com/lampepfl/dotty/issues/16456

som-snytt commented 1 year ago

directly duplicates https://github.com/scala/bug/issues/9261