只做一次,没有状态

Ale*_*Emm 4 state functional-programming scala

我有以下情况:

在初始化(实际上是第一次接收)套接字时,我想检查握手(TLS)中的某些内容,这必须仅在连接初始化时检查,而不是在每次进一步接收时检查.

目前我有一个奇怪的:

   // this is happening outer scope
   var somethingThatGetsComputedinInit = 0

   def receive {
      if (init) {
        somethingThatGetsComputedinInit = doinitstuff(StuffIOnlyGetInitially)
        init = false
      }
    }
Run Code Online (Sandbox Code Playgroud)

虽然它会起作用,但这种气味如此迫切和难看.什么是纯粹的功能解决方案?

wha*_*ley 10

在这种情况下,您希望lazy val在scala中使用修饰符.这在Twitter的Effective Scala中有所体现.请考虑以下对您问题中示例的编辑.

class Foo {
    def doinitstuff() : Int = {
        println("I'm only going to be called once")
        42
    }

    lazy val somethingThatGetsComputedinInit = doinitstuff()

    def receive {
        println(somethingThatGetsComputedinInit)
    }
}
Run Code Online (Sandbox Code Playgroud)

并且Foo调用实例的客户端多次接收将输出以下内容:

 val foo = new Foo                               //> foo  : worksheet.Foo = worksheet.Foo@5853c95f
  foo.receive                                     //> I'm only going to be called once
                                                  //| 42

  foo.receive                                     //> 42
  foo.receive                                     //> 42
Run Code Online (Sandbox Code Playgroud)