vals in a nested singleton object may be initialized to null
See original GitHub issueCompiler version
3.0.0, 3.1.3, 3.2.0 and 3.2.2-RC1-bin-20221006-a6a3385-NIGHTLY
Minimized code
final case class Foo(name: String)
object Foo {
object Foos {
val Name1 = Foo("Apple")
val Name2 = Foo("Banana")
val Name3 = Foo("Cherry")
// Using explicit `new`s prevents the issue
// val Name1 = new Foo("Apple")
// val Name2 = new Foo("Banana")
// val Name3 = new Foo("Cherry")
}
val allFoos: Seq[Foo] = {
import Foos._
Seq(Name1, Name2, Name3)
}
}
object Main {
def main(args: Array[String]): Unit = {
println(Foo.Foos.Name1)
println(Foo.allFoos)
// Accessing in the reverse order (or not accessing Name1 at all) prevents the issue
// println(Foo.allFoos)
// println(Foo.Foos.Name1)
}
}
Output
Foo(Apple)
List(null, null, null)
Expectation
The output should be:
Foo(Apple)
List(Foo(Apple), Foo(Banana), Foo(Cherry))
Replacing any of the commented part of the program above prevents the issue. Also, Scala 2.13.9 produces the expected output without any modification. So, this is a behavior change between 2.13 and 3.
Issue Analytics
- State:
- Created a year ago
- Reactions:1
- Comments:5 (1 by maintainers)
Top Results From Across the Web
C# Singleton pattern with triggerable initialization
Seems like you could do: public sealed class Singleton { IEnumerable<string> Values {get; private set;} private Singleton(bool loadDefaults) ...
Read more >Java Program to Demonstrate the Nested Initialization For ...
A Singleton Class is capable of producing just a single instance. Every Singleton class has a getInstance method which returns its object.
Read more >How to test an object for null in an elegant way in C#?-C
You want the null-coalescing operator combined with the null conditional operator: int addressCount = Output.ScriptPubKey.Addresses?.Length ?? 0;.
Read more >Lazy Initialization in Kotlin - Baeldung
The concept of 'lazy initialization' was designed to prevent unnecessary initialization of objects. In Java, creating an object in a lazy and ...
Read more >AccessClient (Oracle Fusion Middleware Access SDK Java API ...
Creates the singleton object if one does not already exist. In addition, it also performs initialization required before any ASDK api can be...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Related: #11262 #9176
Currently
-Ysafe-init
is not capable of handling static objects.Sample Scala 2 issue
https://github.com/scala/bug/issues/3342