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
}
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: