Reputation: 2845
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
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
Reputation: 9413
You have a cyclic condition here. User extends userTrait
(which intern initializes new User ...
)
Upvotes: 2