Scala Lazy Val Question

邮差的信 提交于 2019-12-02 03:20:00

Note that even your smaller example would have issues (in the REPL):

{
class A(b:B)
class B(a:A)
lazy val a:A = new A(b)
lazy val b:B = new B(a)
a
}
// causes stack overflow error

As soon as a needs to be evaluated therefore constructed, it would require B, which requires A. In order for this to work a or b would have to finish being constructed.

Using by-name parameters allows the smaller example to evaluate.

{
class A(b: => B)
class B(a: => A)
lazy val a:A = new A(b)
lazy val b:B = new B(a)
a
}

Note sure if that'll work for your actor example as well.

Edit: by name params worked locally on 2.8.0. I replaced case class with object to get rid of some deprecation warnings and added start methods on actor1, actor2 and kick the whole thing with actor1 ! Message1. Aside from this I haven't used actor before, so I can't comment more. Here is what I tested:

import scala.actors._

abstract class Message
object Message1 extends Message
object Message2 extends Message

class Actor1(otherActor: => Actor) extends Actor {
def act() {
    loop {
    react {
        case Message1 =>
        println("received message1")
        otherActor ! Message2
        case _ =>
    }
    }
}
}

class Actor2(otherActor: => Actor) extends Actor {
def act() {
    loop {
    react {
        case Message2 =>
        println("received message2")
        otherActor ! Message1
        case _ =>
    }
    }
}
}

{
  lazy val actor1:Actor = new Actor1(actor2)
  lazy val actor2:Actor = new Actor2(actor1)
  actor1.start
  actor2.start
  actor1 ! Message1
}

Prints a bunch of:

received message1
received message2
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!