In Scala IF ELSE can be used in two ways, as statements and as expressions.
General form of an if-else statement:
When we use if as statements, we evaluate a Boolean expression and based on the result of the Boolean expression the code executes a statement. In this case the statement does not return anything by default.
if(BooleanExpression)
{
statement or block 1
}
else
{
statement or block 2
}
General form of an if-else expressions:
When we use if as expression, we evaluate a Boolean expression and based on the result of the Boolean expression the code executes a statement. But in this case the if expression return the result of if expression.
val response = if(BooleanExpression) "condition match" else "condition does not match"
Example:
object Demo {
def main(args: Array[String]) {
val x = 20;
val y = 30;
var res = "";
if (x < 20 || y > 30) {
res = "x == 20 && y == 30";
} else {
res = "x != 20";
}
println(res);
val res2 = if (x != 20) "x == 20" else "x !=20";
println(res2);
println(if (x != 20) "x == 20" else "x !=20");
}
}
/*
x != 20
x !=20
x !=20
*/
Logical Operators
- Scala provides logical operators.
- The binary logical operators combine two boolean expressions into one.
- The unary logical operator switches the value of a boolean expression.
- Binary logical operators have lower precedence than relational operators (they will be evaluated after)
- NOT has the same precedence as negation.
| Operator | Meaning | Kind |
| && | AND | Binary |
| || | OR | Binary |
| ! | NOT | Unary |
Logical Operator Practice
- 2 > 3 && 4 < 5
- false – first operand is false
- 2 < 3 && 4 < 5
- true
- 2 > 3 || 4 < 5
- true
- 2 > 3 || 4 > 5
- false – both operands are false
- !(2 > 3)
- true – operand is false
Leave a Reply