Scala类内部实例化自身导致StackOverflowError问题咨询
Let's break down what's happening here first, using your code and error output:
我定义了如下Scala类:
scala> class test2(private var a:Int) { | var t1 = new test2(10) | println(t1.a) | } defined class test2当我尝试创建该类的对象时,出现了StackOverflowError错误:
scala> var t2 = new test2(5) java.lang.StackOverflowError ... 1024 elided
Root Cause
The problem boils down to infinite recursive instantiation triggered by your class body code. In Scala (and most JVM languages), any code written directly in the class body (not inside a method or constructor block) runs automatically when an instance of the class is created.
Here's the chain reaction that causes the stack overflow:
- You create
t2 = new test2(5)— JVM starts initializing this instance. - During initialization, it hits the line
var t1 = new test2(10)— this creates a brand newtest2instance. - This new
test2instance's initialization also runs the same class body code, so it creates anothertest2instance vianew test2(10). - This loop repeats infinitely, with each new instance creating another one, until the JVM's call stack runs out of space. Hence the
StackOverflowError.
Fix Examples
You need to break this recursive loop by adjusting where you create the nested test2 instance. Here are two common solutions:
1. Move the instance creation to a method
Only create the nested instance when you actually need it, not during class initialization:
class test2(private var a:Int) { def printNestedInstanceValue(): Unit = { val t1 = new test2(10) println(t1.a) } }
Now, the t1 instance is only created when you call printNestedInstanceValue() on your t2 object, no infinite recursion occurs.
2. Use a singleton (companion object) for shared instances
If you only need one instance of test2(10) across all your code, use a Scala companion object to create it once:
class test2(private var a:Int) object test2 { private val sharedInstance = new test2(10) def printSharedInstanceValue(): Unit = println(sharedInstance.a) }
The sharedInstance is created exactly once when the companion object is loaded, so no recursive instantiation happens.
内容的提问来源于stack exchange,提问作者Aditya Agarwal

