Branch on lazily evaluated assignment in Kotlin - kotlin

In Kotlin, how do you branch on multiple conditions, evaluated lazily, some of which may involve variable assignment?
For example, here is a C++ version of this scenario:
int b;
if (a > 0 && (b = getB()) > 0)
branch1(a, b);
else
branch2();
Here is a Swift version, assuming a guard scenario where return is acceptable. Using Optional is a bit hacky, but it works:
guard a > 0, let b = Optional(getB()), b > 0
else { branch2(); return }
branch1(a, b)
In the examples, branch1 and branch2 are function calls for explanatory purposes, but may be inline code in real-world use. Having to factor that code into separate methods may be undesirable.
Kotlin, like Swift, has assignments that don't evaluate to the assigned value. However, Kotlin doesn't have a direct equivalent to guard, which supports assignment with multiple lazy conditions. What is an eloquent way in Kotlin to lazily evaluate a condition that includes an assignment?

I don't think there's an elegant solution to this sort of construct; here are some uglier options.
Perhaps the most direct translation would be along the lines of:
val a: A
if (b && r != null && getA()?.also{ a = it } != null)
branch1(b, r, a) // ERROR: Variable 'a' must be initialized
else
branch2()
…except that the compiler isn't (currently) smart enough to see that a will always have been assigned by the time it's used in branch1().
You could work around that by making it a var, and giving it an initial value — but the only likely value is null, which means making the field nullable and then having to add !! when you use it.  All of which makes it rather ugly — even though the condition is in one place, and getA() is called only if needed:
var a: A? = null
if (b && r != null && getA()?.also{ a = it } != null)
branch1(b, r, a!!)
else
branch2()
A variation might be to split the condition, and always assign a:
val a = if (b && r != null) getA() else null
if (a != null)
branch1(b, r!!, a)
else
branch2()
That works — but now the compiler can't tell that r is non-null, so you need !! there instead.
You could make that slightly simpler with a when (though you need to flip the cases):
when (val a = if (b && r != null) getA() else null) {
null -> branch2()
else -> branch1(b, r!!, a)
}
Ultimately, the problem is that you're trying to get side-effects that only happen under some circumstances, and then use those side-effects back in the condition and the resulting branch — and that's as confusing for humans as it is for the compiler.  (C was my main language for many years, and I always found embedded assignments awkward…)  If I saw such code, I'd consider rewriting it in a more straightforward way, for the benefit of whoever had to maintain it.  In this case, that might be:
if (b && r != null) {
val a = getA()
if (a != null)
branch1(b, r, a)
else
branch2()
} else
branch2()
This is longer-winded, and has to duplicate the branch2() call (though there might be ways around that if the call were very complicated, e.g. by setting a flag).  But it's arguably easier to follow (especially as regards seeing when getA() might be called); a doesn't need to be mutable; and the compiler can see that both r and a cannot be null in the branch1() call, and so smart-casts them.
(By the way, all of these assume that getA() could be expensive and/or have side-effects; if not, there would be simpler alternatives that called it unnecessarily.  Conversely, if more than one assignment were needed, all of these options would get more complicated.)

Related

What is the difference in my code as compared to the code I found on Google to check if my code is right?

in short, the question is, I want to delete the last element of the DOUBLY LINKED LIST and I wrote this function...
fun deleteLast(){
if(isEmpty()){println("list is empty")}
if (head!=null && head?.nextNode == null){
head = null
}else {
tail = tail?.previousNode
tail?.nextNode = null
}
}
I went to the tail without traversing it and made its previous as new tail and new tail next(old tail) as null. And my result is desirable.
after writing this I pinged Google to check if this is right so, I found this...
void pop_back() {
if(this.head != null) {
//1. if head in not null and next of head
// is null, release the head
if(this.head.next == null) {
this.head = null;
} else {
//2. Else, traverse to the second last
// element of the list
Node temp = new Node();
temp = this.head;
while(temp.next.next != null)
temp = temp.next;
//3. Change the next of the second
// last node to null and delete the
// last node
Node lastNode = temp.next;
temp.next = null;
lastNode = null;
}
}
}
I want to ask If my code is right I just want you masters to review it. Thanks in advance!
The question only contains a snippet, not a minimal, reproducible example, so for the sake of argument (based on existing code and the comment) I'm going to assume that the full code looks something like this:
class Node<T>(var previousNode: Node<T>?, var nextNode: Node<T>?, var value: T)
class DoublyLinkedList<T>(var head: Node<T>?, var tail: Node<T>?) {
fun isEmpty() = head == null
// …other methods…
fun deleteLast(){
if(isEmpty()){println("list is empty")}
if (head!=null && head?.nextNode == null){
head = null
}else {
tail = tail?.previousNode
tail?.nextNode = null
}
}
}
Given this, it looks like your code is about right.  There are a few points that could be addressed*, e.g.:
Inside the second if I think it needs to set tail to null as well, for safety.
Inside the second and third branches, you might want to set to null the previousNode and nextNode references in the node you're removing, for the benefit of any other code that still has a reference to it.  (That might also give an extra hint to the garbage collector, though that shouldn't be needed.)
Instead of calling isEmpty(), it'd be simpler and more consistent to check whether head is null.
I'd add an else before the second if.  As it is, the code works for an empty list, but that may be just luck; it'd be much more robust if neither of the other branches could be called on an empty list.  (In some cases, this could let the compiler smart-cast head to non-nullable; but that doesn't happen here because it's mutable.)
In production code, you wouldn't print to stdout like that.  If it's allowed to call deleteLast() on an empty list, then there's no need to print anything; if not (which would be more usual), you'd throw an exception.  (And the method would have a doc comment explaining that.)
The formatting could be improved.
(* In my experience, any code can be improved — even code you've worked on many times before!)
However, you can't compare your code directly to the Google-sourced code, because it looks like that is for a singly-linked list.
A singly-linked list is a much simpler structure.  All it has is a reference to the head node; that has a reference to the next node (and, presumably to the data stored in the node); and so on.  So the only way to reach the end of the list is to traverse all the nodes, as the Google-sourced code does.  (This also means there's often no point in having a separate class to represent the list as a whole; a reference to the first node is all you need.  Many operations can be written concisely with recursive methods.  You can also make it immutable, which has many advantages; that's the primary data structure in some languages.)
Your list, though, has a direct reference to the last node, which of course avoids the need to traverse the entire list to find it.  As your code demonstrates, this means that some operations are much more efficient in double-linked lists.  There are corresponding disadvantages, though: each node takes more memory; there are more references to update when changing the list; it's easier for the list to get into an inconsistent state; and it's less suitable for an immutable list.)

Kotlin "let{}" Doesn't Provide Smart Cast

Just learned Kotlin Nullable type and let{} function which replaces the if (xx != null) {} operation.
But one thing I am confused is that, we all know and I Think the Complier Should Know that when we use let{}, the variable/object who is calling this function is possiblly null, however the complier still requires me to add the safe call operator "?" after the variable name instead of providing Smart Cast like it does in if (xx != null) {}. Why?
My piece of code:
fun main() {
var number1: Int? = null
//val number2 = number1.let { it + 1 } ?: 10 //doesn't work, not quite "smart"
val number2 = number1?.let { it + 1 } ?: 10 //works, must have "?"
println(number1)
println(number2)
}
You've already got answers in the comments, but just to explain the ? thing...
Kotlin lets you make null-safe calls on nullable variables and properties, by adding ? before the call. You can chain this too, by doing
nullableObject?.someProperty?.someFunction()
which evaluates nullableObject, and if it's non-null it evaluates the next bit, otherwise the whole expression evaluates to null. If any part of the chain evaluates as null, the whole expression returns null.
So it has this short-circuiting effect, and you can use the elvis "if null" operator to create a default value if you can't evaluate the whole chain to a non-null result:
nullableObject?.nullableProperty?.someFunction() ?: defaultAction()
and once you introduce the null check in the chain, you have to add it for every call after that - it's basically propagating either the result of the previous bit, or the null it resolved to, so there's a null check at each step
The let block is just a scope function - you use it on a value, so you can run some code either using that value as a parameter or a receiver (a variable or this basically). It also has the side effect of creating a new temporary local variable holding that value, so if the original is a var it doesn't matter if that value changes, because your let code isn't referring to that variable anymore.
So it's useful for doing null checks one time, without worrying the underlying value could become null while you're doing stuff with it:
nullableVar?.let { it.definitelyIsNotNull() }
and the compiler will recognise that and smart cast it to a non-null type. An if (nullableVar != null) check can't guarantee that nullableVar won't be null by the time the next line is executed.

Is `a?.let{} ?: run{}` idiomatic in Kotlin?

I saw the following comment in a S.O. post, and I'm intrigued:
why don't you use if for null checks? a?.let{} ?: run{} is only appropriate in rare cases, otherwise it is not idiomatic – voddan May 15 '16 at 7:29 best way to null check in kotlin?
Why is that construct "only appropriate in rare cases"?
The lead engineer for Kotlin says,
run allows you to use multiple statements on the right side of an elvis operator https://stackoverflow.com/a/51241983/6656019
although I admit that's not actually endorsing it as idiomatic. Both of these posts seem to be from very well respected S.O. Kotlin contributors.
The post that inspired the original comment mentions that the let part of the expression is important if a is mutable. In that case, you'll need a?.let{} ?: run{} instead of if{} else {}.
I find I like the "let Elvis run" construct. Should I avoid it in most cases?
Thanks for any insight.
It's dangerous to conflate foo?.let { bar(it) } ?: baz() with if (foo != null) bar(foo) else baz().
Say you have a function: fun computeElements(): List<Int>? = emptyList()
Consider this code:
val maxElement = computeElements()?.let { it.max() } ?: return
println("Max element was $maxElement")
Compared to:
val list: List<Int>? = computeElements()
val maxElement = if (list != null) list.max() else return
println("Max element was $maxElement")
You may think these are two equivalent forms. However, if you run both, you'll see that the former does not print anything to stdout!
This is because it.max() returns null for an empty list (because there is no max element), which causes the right-hand side of the Elvis expression to be evaluated, and so the function returns early.
In short, ?.let { ... } ?: ... allows both branches of the "if-else" to be evaluated, which is dangerous. Aside from this form not being readable (if-else is universally understood, while let-run is not), subtle bugs can occur.
In that case, you'll need a?.let{} ?: run{} instead of if{} else {}
No, you can omit the run part of run { statement } and use a?.let{} ?: statement.
Should I avoid it in most cases?
You should use it when you need it. E.g. when you want to run multiple statements in that scenario. It is pointed out that that is a rare scenario. Often you will see just a single statement on the right hand side of an elvis operator.
And of course don't use it when you don't need it. Keep the code simple.

What do you call doing assignment in a conditional?

Is there a special name for doing assignment in a conditional? Here is an example of what I am asking about in C:
// Assume a and b have been previously defined and are compatible types
if( (a = b) ) { // <- What do you call that?
//do something
}
A couple friends of mine and I are convinced that there is a name for it, and some other people have agreed that there is one, but we can't find it anywhere. Has anyone here ever heard a term for it?
Assuming that an assignment is intentional, there is no special name for this. C language specification places a very weak requirement on the controlling expression of an if statement:
6.8.4.1-1: The controlling expression of an if statement shall have scalar type.
An assignment expression satisfies this requirement, as long as a and b are scalar. An implicit comparison to zero is performed on the result of this assignment:
6.8.4.1-2: In both forms, the first substatement is executed if the expression compares unequal to 0. In the else form, the second substatement is executed if the expression compares equal to 0.
Note that compilers would issue a warning when they see an assignment like that, because missing second = is a common source of errors. You can prevent these warnings using parentheses, as described in this Q&A.
It doesn’t really have a name, though people do call it various things. If the code follows your question:
if( a = b )...
then common terms are: bug, error, etc. However if b is not a variable but an expression, e.g. as in the common C patterns:
if( (c = getchar()) != EOF )...
while( *q++ = *p++ )...
then it might be called an idiom, pattern, etc.
I don’t know if it has a name but I’d call it “useful feature that nobody understands”.
It is very useful indeed.
We can consider it a slang.
In C++ for example you can use this by declaring a variable directly, and this is useful for safety checks:
if (Object *a = takeObject()) {
// a is not nullptr
}
Or when I don’t want to repeat a statement in a loop:
while (a = next()) {
}
Instead of:
a = next();
while (a) {
a = next();
}
But commonly these are just mistakes which compilers like gcc and clang give warnings about (and they force you to put an horrible double tuple to silence the warning ew!).

Do you usually set the default value before or set it in the else?

Which one of the following do you do:
var = true;
if (...) var = false;
Or
if (...) var = false;
else var = true;
Is there a reason you pick on or the other?
I'm working on the premise that nothing else is happening to var. The next line of code might be something like:
if (var) { ... }
How about var = { ... } directly since it's a boolean?
I prefer the second in Java, doing something like this:
int x;
if (cond) {
x = 1;
} else {
x = 5;
}
because if something is changed later (for example, I turn the else block into an else if), the compiler will tell me that the variable has failed to be initialized, which I might miss if I used your first strategy.
You could also use a ternary operator if your language supports it :)
I would generally only do the first one if there was a chance the IF could fail and the variable must have a default value if it does.
If you set the default, then you reset it again later to something else, although it's a very small amount, its still a waste of resources. So, most of the time, for most of the code, a balanced if/else or even a (?:) syntax, are clearer and more appropriate, except:
Sometimes, if what you doing is building fall-through code (or a decision function), where you start with a specific condition, and then test a whole bunch of other conditions to see if that changes, then you want to definitely set the default first:
int final = 27;
if ( some condition ) final = 86;
if ( another condition ) {
final = 98;
return final;
}
if ( some state ) {
final += 2;
}
return final;
Or something similar to that.
BTW: in your example, if you set 'var', then the next line just tests 'var', you don't really need 'var' do you? If the condition is so ugly that using 'var' helps make it readable, then your probably best to move the condition into it's own function, accepting that the extra function call is there to help readability. In general, you can waste resources, if and only if you get something significant, such as readability, in return.
Paul.
Depends on the context. I would use the second option when it is clear that 'var' needs to be true when IF fails.
I use the first type unless the value to set requires significant computation.
Always the first as many people have said. However it's worth emphasising why, and that's because it makes the program more resistant to future bugs caused by incorrect maintenance.
For example, it's quite common for some additional business condition to arise and a maintenance coder add some extra condition or two inside the if to include more business logic and incorrectly amend the code - for example
if (a==b) {
if (a==c) {
[new logic]
var=false
}
}
else {
var = false
}
On the face of it it looks unlikely, but it happens alarmingly often (in fairness often the situation arises after the original if has got a lot more complex). Putting the initialisation first prevents this.
Do you prefer code that is short and compact, or code that is easier to read?
If you prefer code that is short and compact use
var x = true;
if (...) x = false;
But this can even be "improved". Most languages give initial values, and usually for the boolean type the default is false. So, you could write
var x;
if (...) x = true;
If you prefer code that is easy to read use
if (...) var x = false;
else var x = true;
because it makes your intentions clear.
The performance of both is the same.
Depends on the language. In C++, I would highly recommend setting it to a default as quickly as possible otherwise you risk getting garbage results.
In most other languages, you can be a bit more flexible. In fact, I would argue that it's more readable to explicitly define the conditions than to set a default.
Since the variable is not written to later, for general values I would write the following in Java:
final Type var;
if (cond)
{
var = value1;
}
else
{
var = value2;
}
The Java compiler will catch the error that var is not assigned a value before it is used.
The final keyword expresses the fact that the variable is constant after the conditional.
In your exact case with booleans I would use
final boolean var = !cond;
Using a conditional in this case indicates you are afflicted by "booleanophobia".
In C I would initialize the variable at its declaration.
I generally set the "default" value and use if statements to modify it.
If no default exists then only the if statements.
int timeout = 100;
if (moreTime) timeout = 1000;
int searchOption = null;
if (sometest1) searchOption = 1;
if (sometest2) searchOption = 2;
// then later..
if (searchOption != null)
.....
If the initialization is complex enough that a direct expression can't be cleanly written, I sometimes find it useful to handle this case as
boolean isFoo = determineWhetherFoo(...);
where determineWhetherFoo takes whatever arguments are necessary to make the determination and returns the appropriate boolean result. This makes it very clear what the variable means and what it depends on. Initializing a variable to a possibly-wrong value, followed by a wad of code that may change its value, can sometimes obscure what's being expressed.
Wherever you write an if() also write the else - even if it's empty.
The compiler will optimise it away but it forces you (and any programmers after you) to think about when the if () isn't triggered, what are the consequences?