Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In current Scala, is there a cleaner way to do the "lazy constructor pattern"

The nearest thing to

case class Foo(lazy next: Foo)

that I have been able to come up with is

class Foo(_next: =>Foo) {
    lazy val next = _next
}
object Foo {
    def apply(next: =>Foo) = new Foo(next)
    def unapply(foo: Foo) = Some(foo.next)
}

I found a listed issue add lazy parameters so I guess it will be added someday. In the meantime, does anyone know a cleaner trick than the above?

like image 628
Owen Avatar asked Feb 04 '12 23:02

Owen


1 Answers

Maybe scalaz.Need? This was suggested to me in this answer.

scala> case class Foo(next: Name[Foo])
defined class Foo

scala> lazy val x: Foo = Foo(Need(y)); lazy val y: Foo = Foo(Need(x))
x: Foo = <lazy>
y: Foo = <lazy>

scala> x.next.flatMap(_.next).value eq x
res61: Boolean = true
like image 111
missingfaktor Avatar answered Nov 16 '22 02:11

missingfaktor