5

I like to assign the return value of a function to a variable, but inline. The following is how you would do it not inline.

bool isValid() {
    if(a == b) return true;
    if(a == c) return true;
    return false;
}

bool result = isValid();

What I want is something like

bool result = () {
    if(a == b) return true;
    if(a == c) return true;
    return false;
}

However it displays the error

The argument type 'Null Function()' can't be assigned to the parameter type 'bool'

How do I achieve this?

1
  • Out of interest why do you require this to be inline? Surely just creating a function to handle the logic would just be fine? Commented Aug 6, 2019 at 13:54

1 Answer 1

13

You are defining a lambda expression. This works the same way as in Javascript, Typescript or many other languages.

bool result = () {
    if(a == b) return true;
    if(a == c) return true;
    return false;
}

This code defines an anonymous function of type () -> bool (accepts no parameters and returns bool). And the actual type of the result variable is bool so the compilation is broken (() -> bool and bool are non-matching types).

To make it correct just call the function to get the result.

bool result = () {
    if(a == b) return true;
    if(a == c) return true;
    return false;
}();

Now you define an anonymous function (lambda) and then call it so the result is bool. Types are matching and there's no error.

This is rather an uncommon behaviour to define the function and immediately call it. It's used in Javascript to create a separate scope for variables using closures (some kind of private variables). I would recommend you to move the code to some kind of class or pass a, b, c parameters directly to the function:

bool isValid(a, b, c) {
    /* Your code */
}

It's more generic that way and could be reused. Immediately called lambda is often a sign of bad design.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.