seth
seth

Reputation: 1389

scala - make variable available inside block

Having a function that is used like this:

xpto.withClient {
  client => client.abcd
}

I would like to wrap it in an object:

object X {
  def foo[T](block: => T): T = {
    xpto.withClient {
      client => {
        block
      }
    }
  }
}

to make it possible to be used like this:

object Y {
  def bar : Unit {
    X.foo {
      client.abcd
    }
  }
}

This doesn't seems to be making the client value available inside the block though. Is this possible? Making the client variable available inside the block definition? I've looked around with implicits in Scala but so far no good.

Upvotes: 1

Views: 290

Answers (1)

Michael Zajac
Michael Zajac

Reputation: 55569

That won't work, because block is just something that produces a value of T. It doesn't have the same scope. Supposing that client has type Client, then block should be a function Client => T. foo would then pass the client to block.

def foo[T](block: Client => T): T = {
    xpto.withClient { client =>
        block(client)
    }
}

Or more concisely:

def foo[T](block: Client => T): T = xpto.withClient(block(_))

However, that will change your usage to this:

object Y {
  def bar : Unit {
    X.foo { client =>
      client.abcd
    }
  }
}

Of course, this does nothing but thinly wrap xpto.withClient. The thing is, you need to have a way to pass client down the chain. Doing this implicitly won't really help either, because you still need a client identifier within that anonymous block of code.

Upvotes: 2

Related Questions