Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a function inline to a value in Dart?

Tags:

flutter

dart

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?

like image 900
TheRuedi Avatar asked Dec 23 '22 22:12

TheRuedi


1 Answers

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.

like image 138
Piotr Styczyński Avatar answered Jan 29 '23 07:01

Piotr Styczyński