Is this a language bug or expected behaviour when nesting classes inside methods?

I am getting an unusual stack overflow exception which may be a language bug. The issue arrises when I nest a class and its companion object inside a method.
The following (pointless) code prints “Done!” without a problem:

    object Foo extends App {
      final case class Person(name: String)
      object Person {
    val me = Person("Cameron")
      }
      val _ = Person.me
      println("Done!")
    }

However if I nest some of it in a method the code still compiles, but throws an exception:

 object Foo extends App {
          def method(): Unit = {
            final case class Person(name: String)
            object Person {
              val me = Person("Cameron")
            }
            val _ = Person.me
          }
          method()
          println("Done!")
        }

I used Scala 2.13 to try this out, but first noticed the bug when using 2.12.
Could someone tell me if this is expected behaviour? It seems like it could be a language bug to me?

1 Like

Yes that looks like a bug to me.
If me is a lazy val or a def it doesn’t crash by the way. Or if Person is not a case class, or if you do new Person("Cameron") instead of calling the generated apply method.

Thanks, interesting how it only happens for val and not lazy val or def.
If this is a language bug what is the best way of reporting it? Should I post the same question in scala contributors?

Scala 2 bugs can be reported in Issues · scala/bug · GitHub. This behavior seems to exist in Scala 3 as well, so perhaps you could open an issue there too (Issues · lampepfl/dotty · GitHub) and reference the Scala 2 issue.

Thank you for your help - I’ve raised an issue for both Scala 2 (Stack overflow error when nesting a case class and its companion object inside a method · Issue #12435 · scala/bug · GitHub) and Scala 3 (Stack overflow error when nesting a case class and its companion object inside a method · Issue #13162 · lampepfl/dotty · GitHub)

2 Likes