You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala类内部实例化自身导致StackOverflowError问题咨询

Why does creating an instance of my Scala class cause a 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:

  1. You create t2 = new test2(5) — JVM starts initializing this instance.
  2. During initialization, it hits the line var t1 = new test2(10) — this creates a brand new test2 instance.
  3. This new test2 instance's initialization also runs the same class body code, so it creates another test2 instance via new test2(10).
  4. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:43:06