Dart: warning "info: This function has a return type of 'int', but doesn't end with a return statement") - flutter

I got a warning on the following piece of code, and I don't know why.
List<Map<String, int>> callNoInfo = [];
int getCallNo(String phoneNo) {
callNoInfo.forEach((item) {
if (item.containsKey(phoneNo)) {
return item[phoneNo];
}
});
return 0;
}
The warning is:
This function has a return type of 'int', but doesn't end with a return statement. (missing_return at [project_name] lib\helper\call_no.dart:35)
Can anyone tell me why this happens? thanks in advance

In the forEach method, you are creating a lambda function without explicitly defining the return type, so Dart is attempting to infer it from the return statements. If we pull the function out of the forEach method, it might help to see what I mean:
...
(item) {
if (item.containsKey(phoneNo)) {
return item[phoneNo];
}
}
...
The function includes a return statement that returns item[phoneNo], which is an int value. Using this, Dart infers that the return type of this lambda function is int. However, now that it knows this, it also notices that if the code execution does not enter the if block, there is no return statement to match the else side of the if condition. If the item object does not contain the key phoneNo, what is the method going to return?
(The answer is that the method will implicitly return null which is why the message is only a warning and not a compiler error, but the warning appears because this probably wasn't intentional by you the developer and also as a nudge to help you make your code less reliant on invisible Dart runtime magicks.)
To fix this, there needs to be another return outside of the if block:
...
(item) {
if (item.containsKey(phoneNo)) {
return item[phoneNo];
}
return 0;
}
...
However, now there's a different problem. The forEach method on lists has the following signature:
forEach(void f(E element)) → void
In fact, there are two problems. First, the method passed as the parameter needs to have a return type of void, and the forEach method itself also has a return type of void. This means that you cannot return values from within the forEach method at all.
The thing about the forEach method is that it is intended to iterate over the collection and process each of the values within it. It's not meant to (and can't) search for a value and return it once it's found. Furthermore, the iteration is exhaustive, meaning once you start it, the method cannot be stopped until each and every element in the collection has been iterated over.
Which is why, as the other answers have pointed out, what you really should be doing is using a for or for in loop:
List<Map<String, int>> callNoInfo = [];
int getCallNo(String phoneNo) {
for(var item in callNoInfo) {
if (item.containsKey(phoneNo)) {
return item[phoneNo];
}
}
return 0;
}
(I'm not sure why you don't get a compiler error for assigning a lambda function with a return value of int to the forEach method which clearly is requesting a one with a void return type. But if I had to guess, I'd say the Dart runtime treats them as compatible and reconciles the difference in return type by simply discarding the return value of the lambda function.)

You don't have an else case for the if statement inside the forEach loop. Even though you might have one at the end, it still is expecting a case everywhere.
List<Map<String, int>> callNoInfo = [];
int getCallNo(String phoneNo) {
callNoInfo.forEach((item) {
if (item.containsKey(phoneNo)) {
return item[phoneNo];
}
// you don't have a case for here since it's in a callback
});
return 0;
}
However, you could do this which uses a for in loop:
List<Map<String, int>> callNoInfo = [];
int getCallNo(String phoneNo) {
for (var item in callNoInfo) {
if (item.containsKey(phoneNo)) {
return item[phoneNo];
}
}
return 0;
}

Related

Proper using of question mark (null safety) in flutter

Is it equal in flutter null safety?
if(widget.mapPickerController != null){
widget.mapPickerController!.mapMoving = mapMoving;
widget.mapPickerController!.mapFinishedMoving = mapFinishedMoving;
}
widget.mapPickerController?.mapMoving = mapMoving;
widget.mapPickerController?.mapFinishedMoving = mapFinishedMoving;
Both versions should end up doing the same thing. When null-safety enabled, ?. short-circuits the rest of the expression, so if the receiver is null, the rest of the expression (including the right-hand-side of the assignment) won't be evaluated. You can observe that in the following example:
class Foo {
int value = 0;
}
int bar() {
print('Called bar');
return 42;
}
void main() {
Foo? foo = null;
foo?.value = bar();
}
where running it generates no errors and shows that bar() is never called.
That said, the second version using ?. is much less clear (which is evident from the apparent confusion in the several deleted answers) and therefore probably should be avoided.
The best way would be to introduce a local variable:
final mapPickerController = widget.mapPickerController;
if (mapPickerController != null){
mapPickerController.mapMoving = mapMoving;
mapPickerController.mapFinishedMoving = mapFinishedMoving;
}
and then you don't need to use the null-assertion operator at all, and it's slightly more efficient since you check for null only once.

How to accept both ref and non ref values as a function argument

I want to take any kind of values inside a function (r/lvalue) and I also want to ensure that the value will not be mutated in the scope of the function, even if the value itself is not a const.
struct Tree(T) {
T item;
Tree!T* parent, left, right;
this(T item) {
this.item = item;
}
Tree!T* searchTree(const ref T item) {
if (&this is null)
return null;
if (this.item == item)
return &this;
return (this.item < item) ? this.right.searchTree(item) : this.right.searchTree(item);
}
}
unittest {
auto text1 = "Hello", text2 = "World";
auto tree2 = Tree!string(text1);
assert(tree2.searchTree(text2) is null);
assert(tree2.searchTree(text1) !is null);
}
This works with ref parameters however if I give int literals to the function, it fails:
auto tree1 = Tree!int(4);
assert(tree1.searchTree(5) is null);
assert(tree1.searchTree(4) !is null);
Templates to the rescue! D has a feature called auto ref that automatically generates the overloads for ref and non-ref parameters. The only requirement is that the function must be a template.
For your searchTree function, that means it needs to have this signature:
Tree!T* searchTree()(const auto ref T item)
With that simple change, your code should compile and do The Right Thing™.
there is currently an experimental compiler switch for DMD that allows this.
try adding "-preview=rvaluerefparam" to your compiler switches.

From RxJava2, How can I compare and filter two observables if the values are equal?

I am new to RxJava2.
I am trying to get a list of Transaction object both from cache and from server.
I want to compare the server value to cache value and if the server value is the same, then ignore it.
I was able to do it easily using .scan() because we can return null and when null is returned from the .scan() the value got ignored(filtered).
RxJava 1
private Observable<List<Transaction>> getTransactionsFromCacheAndServer() {
return Observable.concat(
getTransactionsFromCache(),
getTransactionsFromServer()
)
.scan((p1, p2) -> {
if (p1 == null && p2 != null) {
return p2;
} else if (p1 != null && !isListSame(p1, p2)) {
return p2;
} else {
return null;
}
});
}
With RxJava 2, since I cannot return null anymore, things are not easy.
RxJava 2
private Observable<List<Transaction>> getTransactionsFromCacheAndServer() {
return Observable.concat(
getTransactionsFromCache(),
getTransactionsFromServer()
)
.map(FilterObject::new)
.scan((filterObject1, filterObject2) -> {
List<Transaction> p1 = (List<Transaction>)filterObject1.value;
List<Transaction> p2 = (List<Transaction>)filterObject2.value;
if (p1.size() == 0 && p2.size() > 0) {
return filterObject2;
} else if (!isListSame(p1, p2)) {
return filterObject2;
} else {
filterObject2.filter = true;
return filterObject2;
}
})
.filter(filterObject -> !filterObject.filter)
.map(filterObject -> (List<Transaction>)filterObject.value);
}
Where FilterObject is:
public class FilterObject {
public Object value;
public boolean filter;
public FilterObject(Object value) {
this.value = value;
}
}
Even though I can achieve the same thing using above method, it seems very ugly. Also I had to include two maps which might not be so performance friendly.
Is there a simple/clean way to achieve what I want?
I don't think there is a generic solution to this problem, since an empty list and a list that needs to be filtered (which happens to be empty in all cases) are two different things (the output of the scan) and needs to be handled differently.
However, in your particular case you never emit an empty list, except maybe for the first output.
(I am using String instead Transaction, shouldn't matter)
private Observable<List<String>> getTransactionsFromCacheAndServer() {
return Observable.concat(
getTransactionsFromCache(),
getTransactionsFromServer()
)
.filter(list -> !list.isEmpty())
// If you prefer a consistent empty list over the first
// empty list emission getting filtered
.startWith((List<String>) Collections.EMPTY_LIST)
// Newly emitted value cannot be empty, it only depends only on the comparison
.distinctUntilChanged(this::isListSame);
}
That's the closest I could get with as few operators as possible. Hope it solves your problem.
Based on andras' answer, I modified little bit to achieve what I want.
private Observable<List<String>> getTransactionsFromCacheAndServer() {
return Observable.concat(
getTransactionsFromCache(),
getTransactionsFromServer()
)
.filter(list -> !list.isEmpty())
.distinctUntilChanged(this::isListSame)
.switchIfEmpty(Observable.just(new ArrayList<>()));
}
Andreas' answer will always receive an empty list and then a real data.
My solution above will receive:
1. Data from cache (and then data from server if different)
2. Empty list if both cache and server returns Empty list.

Promise working without resolving it in protractor

The below is my page object code
this.getRowBasedOnName = function (name) {
return this.tableRows.filter(function (elem, index) {
return elem.element(by.className('ng-binding')).getText().then(function (text) {
return text.toUpperCase().substring(0, 1) === name.toUpperCase().substring(0, 1);
});
});
};
the above function is called in the same page object in another function, which is
this.clickAllProductInProgramTypeBasedOnName = function (name) {
this.getRowBasedOnName(name).then(function (requiredRow) {
requiredRow.all(by.tagName('label')).get(1).click();
});
};
but the above code throws an error in the console as requiredRow.all is not a function
but when i do the following :
this.clickAllProductInProgramTypeBasedOnName = function (name) {
var row = this.getRowBasedOnName(name)
row.all(by.tagName('label')).get(1).click();
};
this works fine and clicks the required element.
But this.getRowBasedOnName() function returns a promise, which should and can be used after resolving it uisng then function. How come it is able to work by just assigning it to a variable?
When you resolve the result of getRowBasedOnName(), which is an ElementArrayFinder, you get a regular array of elements which does not have an all() method.
You don't need to resolve the result of getRowBasedOnName() at all - let it be an ElementArrayFinder which you can chain with all() as in your second sample:
var row = this.getRowBasedOnName(name);
row.all(by.tagName('label')).get(1).click();
In other words, requiredRow is not an ElementArrayFinder, but row is.

insertion sort on linked list

//I wrote java code for insertion method on doubly linked list but there is a infinite loop //when I run it. I'm trying to find a bug, but have not found so far. any suggestions?
//it is calling a helper function
public IntList insertionSort ( ) {
DListNode soFar = null;
for (DListNode p=myHead; p!=null; p=p.myNext) {
soFar = insert (p, soFar);
}
return new IntList (soFar);
}
// values will be in decreasing order.
private DListNode insert (DListNode p, DListNode head) {
DListNode q=new DListNode(p.myItem);
if(head==null){
head=q;
return head;
}
if(q.myItem>=head.myItem){
DListNode te=head;
q.myNext=te;
te.myPrev=q;
q=head;
return head;
}
DListNode a;
boolean found=false;
for(a=head; a!=null;){
if(a.myItem<q.myItem){
found=true;
break;
}
else{
a=a.myNext;
}
}
if(found==false){
DListNode temp=myTail;
temp.myNext=q;
q.myPrev=temp;
myTail=q;
return head;
}
if(found==true){
DListNode t;
t=a.myPrev;
a.myPrev=q;
t.myNext=q;
q.myPrev=t;
q.myNext=a;
}
return head;
}
Your code is a bit hard to read through but I noticed a few problems
First:
handling the case where you are inserting a number at the head of the list:
if(q.myItem>=head.myItem){
DListNode te=head;
q.myNext=te;
te.myPrev=q;
q=head;
return head;
}
specifically the line q=head; and the return. q=head can be removed, and it should return q not head because q is the new head. I think what you meant to do was head=q; return head;. The current code will essentially add the new node on the front but never return the updated head so they will "fall off the edge" in a way.
Second:
I am assuming myTail is some node reference you are keeping like myHead to the original list. I don't think you want to be using it like you are for the sorted list you are constructing. When you loop through looking for the place to insert in the new list, use that to determine the tail reference and use that instead.
DListNode lastCompared = null;
for(a=head; a!=null; a=a.myNext) {
lastCompared = a;
if(a.myItem<q.myItem) {
break;
}
}
if( a )
{
// insert node before a
...
}
else
{
// smallest value yet, throw on the end
lastCompared.myNext = q;
q.myPrev = lastCompared;
return head;
}
Finally make sure myPrev and myNext are being properly initialized to null in the constructor for DListNode.
disclaimer I didn't get a chance to test the code I added here, but hopefully it at least gets you thinking about the solution.
A couple stylistic notes (just a sidenote):
the repeated if->return format is not the cleanest in my opinion.
I generally try and limit the exit points in functions
There are a lot of intermediate variables being used and the names are super
ambiguous. At the very least try and use some more descriptive
variable names.
comments are always a good idea. Just make sure they don't just explain what the code is doing - instead try and
convey thought process and what is trying to be accomplished.