vumaasha
vumaasha

Reputation: 2845

StackoverFlow error on trait creating self object

I am trying to define an User object which extends a trait. Trait contains a collection of user object. When I try to create a new user. I get Stackoverflow error, I am not able to understand why

scala> :paste
// Entering paste mode (ctrl-D to finish)

case class User(email:String) extends userTrait


trait userTrait {
  self:User =>
  val administrators = new User("[email protected]")::new User("[email protected]")::Nil
  def isAdminstrator = administrators.contains(this)
}

// Exiting paste mode, now interpreting.

defined class User
defined trait userTrait

scala> new User("test")
java.lang.StackOverflowError
  ... 1024 elided

Upvotes: 0

Views: 120

Answers (2)

user5102379
user5102379

Reputation: 1512

"How do I initialize that collection ?" You can simply prepend val administrators with lazy

trait userTrait {
  self: User =>
  /* >>> */ lazy val administrators = 
    new User("[email protected]") :: new User("[email protected]") :: Nil
  def isAdminstrator = administrators.contains(this)
}
case class User(email: String) extends userTrait

println(new User("test").isAdminstrator)
// prints false
println(new User("[email protected]").isAdminstrator)
// prints true

Upvotes: 3

nitishagar
nitishagar

Reputation: 9413

You have a cyclic condition here. User extends userTrait (which intern initializes new User ...)

Upvotes: 2

Related Questions