The difference between &&
and and
and the difference between ||
and or
:
&&
and||
use short-circuit evaluation whileand
andor
always evaluate every condition
But apart from that, I get different behaviour for the following example:
Using &&
, this snippet perfectly works:
var str1: String? = "Good Morning"
var str2: String? = "How's it going"
if (str1 != null && str2 != null) {
println(str1.length + str2.length)
}
When I replace the &&
with and
I have to add parenthesis around both conditions, otherwise the compiler seems to get confused because I get the error: Operator '!=' cannot be applied to 'String?' and 'BigInteger'
Using and
and adding parenthesis:
var str1: String? = "Good Morning"
var str2: String? = "How's it going"
if ((str1 != null) and (str2 != null)) {
println(str1.length + str2.length)
}
But this last snippet throws:
Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type String?
Shouldn't both expressions do precisely the same? Evaluate both conditions and only execute the println
when both String
values are non-null
? What is the difference?