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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With