Reputation: 16718
Is there anything that I should watch out for when I use classes that keeps themselves as members?
This works (it's from a Scala Worksheet in Scala-IDE), but will this bite me at some point, ie Is this normal practice or bad practice and why?
object Play {
println("Playing a bit") //> Playing a bit
case class X(a: Int = 1, x: List[X]){
}
val y = X(3, List()) //> y : Play.X = X(3,List())
val z = X(5, List(X(6, List()))) //> z : Play.X = X(5,List(X(6,List())))
println(z) //> X(5,List(X(6,List())))
println(z.x.head.a) //> 6
}
Upvotes: 1
Views: 89
Reputation: 52681
This is a perfectly fine use of a case class. Case classes are great for defining Recursive structures like this.
For instance, if I wanted to define my own linked-list class, I could use a case class to facilitate easy pattern-matching functionality:
trait MyList[T]
case class Link[T](head: T, tail: MyList[T]) extends MyList[T]
case class End[T]() extends MyList[T]
@tailrec
def last[T](list: MyList[T]): Option[T] =
list match {
case End() => None
case Link(head, End()) => Some(head)
case Link(head, tail) => last(tail)
}
println(last(Link(1, Link(2, Link(3, End()))))) // Some(3)
println(last(Link(1, End()))) // Some(1)
println(last(End())) // None
Upvotes: 3