Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do something only once, without state

I have the following situation:

Upon initialitation (actually first receive) of a socket I want to check something in the handshake (TLS), this has to be only checked upon connection initialization and not on every further receive.

Currently I have an odd:

   // this is happening outer scope
   var somethingThatGetsComputedinInit = 0

   def receive {
      if (init) {
        somethingThatGetsComputedinInit = doinitstuff(StuffIOnlyGetInitially)
        init = false
      }
    }

Although it would work, this smells so imperative and ugly. What would be a purely functional solution to this?

like image 570
AlessandroEmm Avatar asked Dec 07 '22 04:12

AlessandroEmm


1 Answers

This is a case where you want to make use of the lazy val modifier in scala. This is suggested in Twitter's Effective Scala. Consider the following edits to the example in your question.

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

    lazy val somethingThatGetsComputedinInit = doinitstuff()

    def receive {
        println(somethingThatGetsComputedinInit)
    }
}

and a client of an instance of Foo calling receive multiple times would output the following:

 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
like image 114
whaley Avatar answered Dec 25 '22 11:12

whaley