0

If a lambda is frequently used, it is considered to reuse the same instance instead of creating new instances repeatedly.

How can I minimize the number of captured variables in lambda expressions?

4
  • 1
    Curious to see if this question can be answered in a language agnostic way. If you had included a specific language I would vote to close it, because how to do X in language Y belongs on StackOverflow.
    – Rik D
    Dec 26, 2023 at 19:38
  • 8
    Stepping back a bit, what improvement to your system are you hoping to obtain by mimizing the number of captured variables? Dec 26, 2023 at 19:59
  • 3
    "A lambda expression is typically instantiated each time it is invoked." - em, no. A lambda expression is instantiated when the code which instantiates it is executed, and invoked when the code which invokes it is executed. Moreover, regardless whether this statement is right or wrong, it is unclear what this has to do with your question. And when you don't intend to invest more time into the question for clarifying what you are actually after, do yourself and us a favor and delete the question ASAP. Thanks.
    – Doc Brown
    Dec 27, 2023 at 21:36
  • 1
    A lambda expression is isomorphic to a class with a single method and a single constructor. You are asking "how can I minimise the number of members in a class with one method"
    – Caleth
    Dec 28, 2023 at 19:39

1 Answer 1

2

An obvious way is to capture a reference to an object. That reference is just one variable and allows you to access many values.

1
  • 1
    I would recommend to design such a captured object in an immutable fashion, otherwise can introduce all kinds of unwanted side effects into a lambda expression.
    – Doc Brown
    Dec 27, 2023 at 21:40

Not the answer you're looking for? Browse other questions tagged or ask your own question.