Reputation: 121
I'm dealing with recursion and I was wondering if there is anyway to reference the variable (that is the result of a function) inside of another function. Here is the part of the code in question.
# functional way
ListNode x = maxNode(list.next);
if(list.info.compareTo(x.info) < 0) {
return x;
}
# ideal way
if(list.info.compareTo(ListNode y = maxNode(list.next)) < 0) {
return y;
}
Upvotes: 0
Views: 42
Reputation: 2727
It is possible to have the variable defined before hand and then set in the if statement
ListNode y;
if(list.info.compareTo((y = maxNode(list.next)).info) < 0)
return y;
But it is a bit more readable to just set it before hand
ListNode y = maxNode(list.next);
if(list.info.compareTo(y.info))
return y;
I would only suggest doing the setting in a checking statement for loops, as it can help with readability in that case
ListNode y = list;
while((y = y.next) != null)
//dostuff
This form of while loop could also be more easily represented as a for loop
for(ListNode y = list; y != null; y = y.next)
//dostuff
Upvotes: 1