I'm a beginner at Scala (I read a cup book but I don't understand many things) This is my first time asking stack overflow questions, so please let me know if there are any points that I don't understand.
Describes a bidirectional circular link list.
case class Ring(a:Int, var priv:Ring, var next:Ring){
if(priv!=null)priv.next=this
if(next!=null)next.priv=this
}
object Test extensions App {
valr1 = Ring (1, null, null)
val r2 = Ring(2,r1,null)
val r3 = Ring(3, r2, r1)
}
In scala, it is written as a book to use val instead of var, so I would like to use priv and next as val, but I couldn't.
After building the list, I will not change priv or next, so would it be possible to make it val?
Typically, delay evaluation is used to configure invariant reciprocal data.In the case of scala, it can be achieved by using the name calling with lazy val
.
class Ring(vala:Int,p:=>Ring,n:=>Ring){
lazy val prev=p
lazy val next=n
}
object Test extensions App {
val r1 = new Ring (1, r3, r2)
val r2 —Ring = new Ring(2,r1,r3)
val r3 —Ring = new Ring(3, r2, r1)
/*
var node = r1
do{
println(node.a)
node = node.next
} while(nodener1)
do{
println(node.a)
node = node.prev
} while(nodener1)
*/
}
Note that r2
, r3
cannot be a case class because they are calling names.
© 2024 OneMinuteCode. All rights reserved.