var myAge = 22
var sisterAge = 21
myAge == sisterAge // false
myAge !== sisterAge // true
Conditional Expression
Equality Operators
Range operator
var height = 46 // inches
if (height in 1..53) {
println("Sorry, you must be at least 54 inches to ride the coaster")
}
// Prints: Sorry, you must be at least 54 inches to ride the roller coaster
When expression
var grade = "A"
when (grade) {
"A" -> println("Great job!")
"B" -> println("Great job!")
"C" -> println("You passed!")
else -> println("Close! Be sure to prepare more next time!")
}
// print: Great job!
Nested conditions
var studied = true
var well Rested = true
if (wellRested) {
println("Good luck today!")
if (studied) {
println("You should prepare for the exam!")
} else {
println("Spend a few hours studying before the exam!")
}
}
// Print: Good luck today!
// print: You should be ready for the exam!
Evaluation order
!true && (false || true) // false
/\*
(false || true) is evaluated first to return true.
Then, evaluate !true && true and return the final result false
\*/
!false && true || false // true
/\*
!false is evaluated first to return true.
Then true && true is evaluated, returning true.
then, true || evaluates to false and eventually returns true
\*/
NOT operator
var hungry = true
var full = false
println(!hungry) // false
println(!full) // true
Or operator:||
var late = true
var skipBreakfast = true
var underslept = false
var checkEmails = false
// true OR true
println(skipBreakfast || late) // true
// true OR false
println(late || checkEmails) // true
// false OR true
println(underslept || late) // true
// false OR false
println(checkEmails || underslept) // false
AND operator: &&
var humid = true
var raining = true
var shorts = false
var sunny = false
// true AND true
println(humid && raining) // true
// true AND false
println(humid && shorts) // false
// false AND true
println(sunny && raining) // false
// false AND false
println(shorts && sunny) // false
Logical Operators
var humid = true
var raining = true
var jacket = false
println(!humid)
// print: false
println(jacket && raining)
// print: true
println(humid || raining)
// print: true
Comparison Operators
var myAge = 19
var sisterAge = 11
var cousinAge = 11
myAge > sisterAge // true
myAge < cousinAge // false
myAge >= cousinAge // true
myAge <= sisterAge // false
Else-If expressions
var age = 65
if (age < 18 ) {
println("You are considered a minor")
} else if (age < 60) {
println("You are considered an adult")
} else {
println("You are considered senior")
}
// print: you are considered senior
Else-expression
var rained = false
if (rained) {
println("No need to water the plants today.")
} else {
println("The plant needs to be watered!")
}
// print: The plant needs watering!
If expression
var morning = true
if (morning) {
println("Rise and shine!")
}
// Print: Rise and shine!
Comments