scalascala-2.9

stack overflow on overriding lazy val in scala


I have trimmed my code down to the following. I am confused why I am getting a stack overflow between the two filter methods (one in my trait and one in my superclass)

object TestingOutTraits {

  val TestHandler = new Object with MySuper with MyTrait {
    override lazy val createdFilter = {
      "second part"
    }
  }

  def main(args: Array[String]) = {
    val result : String = TestHandler.start()
    System.out.println("result="+result)
  }
}

trait MySuper {

  protected def filter: String = {
    "first part to->"
  }

  def start() = {
    filter
  }
}

trait MyTrait { self: MySuper =>

  lazy val createdFilter = {
    "override this"
  }

  protected override def filter: String = {
    self.filter + createdFilter
  }
}

This is scala 2.9. Any ideas what is going on here?

EDIT: The stack trace makes no sense on how it jumps back and forth too(I should have included it in original post)...

at MyTrait$class.filter(TestingOutTraits.scala:34)
at TestingOutTraits$$anon$1.filter(TestingOutTraits.scala:4)
at MyTrait$class.filter(TestingOutTraits.scala:34)
at TestingOutTraits$$anon$1.filter(TestingOutTraits.scala:4)

thanks, Dean


Solution

  • The call self.filter in MyTrait.filter invokes itself, leading to infinite recursion that blows the stack.

    Instead, have MyTrait extend MySuper, and use super.filter:

    trait MyTrait extends MySuper {
      lazy val createdFilter = {
        "override this"
      }
    
      protected override def filter: String = {
        super.filter + createdFilter
      }
    }