ex1:
// do something ...
return $this->redirect()->toRoute(..);
return false;
ex2:
public function myTest(){
return $this->redirect()->toRoute(..);
}
// do something ...
myTest();
return false;
When do I use ex1, my code stopped and return, didn't run return false;
the same code below ex2, return false ran.
Please help me, why such ???
in ex1 return false; is not being reached because return exits the function you're currently running in. So calling $this->redirect()->toRoute(..) will run, then execution will end for that function.
in ex2, you're defining a function myTest(), so the return $this->redirect()->toRoute(..); exits the myTest() function with the return value of toRoute().
Then the next line of code, return false runs and exits the function it resides in with the value of false.
Once you call return, any code following that statement will be ignored. Sort of like a break; or continue; statement in a for loop.
You would need to add logic, like an if or switch statement and determine whether you want to return false or return $this->redirect()->toRoute(..);.
For example:
function someFunction() { // someFunctionCalled
if (codingIsFun) { // Coding is fun
$foo = myTest(); // $foo is true, since myTest() returns true.
return $foo; // Exit "someFunction()" with a return value of $foo (true)
// any remaining code in "someFunction()" will not be executed.
}
// Some people will put this line in an "else" block,
// but it isn't necessary, this code will only execute if
// coding is not fun.
return false; // Coding is not fun.
}
function myTest() {
return true;
}
// Call someFunction, if coding is fun, $isCodingFun will == true,
// If not, $isCodingFun will == false.
$isCodingFun = someFunction();
Related
In case of function returns a Future, should I return pure bool or construct a future with bool?
Future<bool> loginSite() async {
...
return Future.value(false);
// or
// return false;
}
If the function is marked async simply use return false. It's easier to read and it has the same behaviour.
Side note: there's even a language request to disallow returning futures from async functions.
If you're using async, you can simply ignore Future.value and return bool:
Future<bool> f() async { // <-- Has async
// ...
return false;
}
In absence of async, use Future.value:
Future<bool> f() { // <-- Doesn't have async
// ...
return Future.value(false);
}
I know that in order to run a file with assertions enabled I must run it with the --enable-asserts flag like that:
dart --enable-asserts file_name.dart
How do I verify whether assertions are enabled inside of the main function and print something if they are not?
Not sure if there are any correct way to do this but you can "hack" something together like this:
void main() {
if (assertEnabled()) {
print('Asserts enabled!');
} else {
print('Asserts not enabled!');
}
}
bool assertEnabled() {
try {
assert(false);
return false;
} catch (_) {
return true;
}
}
For an approach that doesn't involve throwing and catching AssertionError, you can take advantage of the assert expression being evaluated only if assertions are enabled:
void main() {
if (assertEnabled()) {
print('Asserts enabled!');
} else {
print('Asserts not enabled!');
}
}
bool assertEnabled() {
var result = false;
assert(result = true);
return result;
}
In general, you also can create and invoke an anonymous function to execute arbitrary code only if assertions are enabled:
assert(() {
print('Asserts enabled!');
return true;
}());
The Fat Arrow is syntactic sugar, like described here
But if I remove return in(look for: future.then(print); // << Removed return) then it complains about missing return?:
Hmm, or am I missing a "return-return" kind og thing...
import 'dart:async';
main() {
printsome();
print("After should be called first...");
}
Future<void> printsome() {
final future = delayedFunction();
future.then(print); // << Removed return
// You don't *have* to return the future here.
// But if you don't, callers can't await it.
}
const news = '<gathered news goes here>';
const oneSecond = Duration(seconds: 1);
Future<String> delayedFunction() =>
Future.delayed(oneSecond, () => news);
I get this warning:
[dart] This function has a return type of 'Future<void>', but doesn't end with a return statement. [missing_return]
The => expr implicitly returns the result of expr, so if you want to replace it with a function body { return expr; } you need to add return, otherwise null will be implicitly returned.
You declared a function with return type Future<void> and DartAnalyzer warns you that your function is not returning such a value.
You can either add async which makes the function implicitly return a Future
Future<void> printsome() async {
final result = await delayedFunction();
}
or if you don't want to use async you can just add return
Future<void> printsome() {
final future = delayedFunction();
return future.then(print); // return the Future returned by then()
}
Is it possble to change the whay the logical or || statement is executed in dart.
For example. I have the functions foo() and boo() which have a return type of bool. If i write
(foo() || boo()) ? /* A */ : /* B */;
and foo() returns true boo() would not be executed. I would like to be able to change that, but couldn't find a way to do so.
I was surprised to see that this will not help:
bool helper = false;
helper = helper || foo();
helper = helper || boo();
(helper) ? /* A */ : /* B */
boo() is only executed when foo() returns true, because the result would be false anyway (short-circuit). You have to force explicit execution like:
var f = foo();
var b = boo();
(f || b) ? print('false') : print('true');
If you want to use it inline you can use a custom method like mentioned by #AlexandreArdhuin or
[foo(), boo()].reduce((v1, v2) => v1 || v2)
? print('false') : print('true');
Try it in DartPad.
You can not use | in dart but you can write an helper function like or and have a syntax quite close:
main() {
if (or([foo(), boo()])) {
print('ok');
}
}
bool or(List<bool> values) => values.fold(false, (t, e) => t || e);
bool foo() {
print("foo");
return true;
}
bool boo() {
print("boo");
return true;
}
Try it in DartPad.
non-short-circuit boolean operators is the phrase you are looking for, and it is not possible at the moment, see https://github.com/dart-lang/sdk/issues/1080
I'm trying to get my head around the module pattern in Javascript and have come across various different ways that I can see to do it. What is the difference (if any) between the following:
Person = function() {
return {
//...
}
};
person1 = Person();
function Person2() {
return {
//...
}
}
person2 = Person2();
person3 = function() {
return {
//...
}
}();
person4 = (function() {
return {
// ...
}
})();
person5 = (function() {
return {
// ...
}
}());
They all seem to do the same thing to me.
// This creates a function, which then returns an object.
// Person1 isn't available until the assignment block runs.
Person = function() {
return {
//...
}
};
person1 = Person();
// Same thing, different way of phrasing it.
// There are sometimes advantages of the
// two methods, but in this context they are the same.
// Person2 is available at compile time.
function Person2() {
return {
//...
}
}
person2 = Person2();
// This is identical to 'person4'
// In *this* context, the parens aren't needed
// but serve as a tool for whoever reads the code.
// (In other contexts you do need them.)
person3 = function() {
return {
//...
}
}();
// This is a short cut to create a function and then execute it,
// removing the need for a temporary variable.
// This is called the IIFE (Immediate Invoked Function Expression)
person4 = (function() {
return {
// ...
}
})();
// Exactly the same as Person3 and Person4 -- Explained below.
person5 = (function() {
return {
// ...
}
}());
In the contexts above,
= function() {}();
= (function() {}());
= (function() {})();
All do exactly the same thing.
I'll break them down.
function() {}();
<functionExpression>(); // Call a function expression.
(<functionExpression>()); // Wrapping it up in extra parens means nothing.
// Nothing more than saying (((1))) + (((2)))
(<functionExpression>)();
// We already know the extra parens means nothing, so remove them and you get
<functionExpression>(); // Which is the same as case1
Now, all of that said == why do you sometimes need parens?
Because this is a *function statement)
function test() {};
In order to make a function expression, you need some kind of operator before it.
(function test() {})
!function test() {}
+function test() {}
all work.
By standardizing on the parens, we are able to:
Return a value out of the IIFE
Use a consistent way to let the reader of the code know it is an IIFE, not a regular function.
The first two aren't a module pattern, but a factory function - there is a Person "constructor" that can be invoked multiple times. For the semantic difference see var functionName = function() {} vs function functionName() {}.
The other three are IIFEs, which all do exactly the same thing. For the syntax differences, see Explain the encapsulated anonymous function syntax and Location of parenthesis for auto-executing anonymous JavaScript functions?.
I've found a extremely detail page explaining this kind of stuff
Sth called IIFE
Hope will help.