If As An Expression
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 31 of 93.
You've seen how if can be used inline to choose between two values. But when your if-else blocks contain multiple statements, you can still use the entire structure as an expression: the last expression in each branch becomes the returned value.
fun main() {
val score = 85
val message = if (score >= 60) {
val grade = "passing"
"You got a $grade score!"
} else {
val grade = "failing"
"You got a $grade score."
}
println(message) // Prints: You got a passing score!
}Each branch can contain multiple statements, but the last expression in the branch is what gets returned and assigned to the variable. In this case, the string on the final line of each block becomes the value of message.
This also works with else if chains:
fun main() {
val temperature = 25
val description = if (temperature > 30) {
"Hot"
} else if (temperature > 20) {
"Warm"
} else {
"Cool"
}
println(description) // Prints: Warm
}When using if as an expression, the else branch is required: Kotlin needs to guarantee a value is returned regardless of which condition is true.
Challenge
EasyYou are provided with the following variable:
val hours = 45Use an if expression with multiple statements in each branch to determine a worker's pay status and create a message.
Create a variable payStatus using an if expression:
- If
hoursis greater than 40:- Create a variable
overtimeequal tohours - 40 - The last expression should be
"Overtime: $overtime extra hours"
- Create a variable
- Otherwise:
- Create a variable
remainingequal to40 - hours - The last expression should be
"Regular: $remaining hours until overtime"
- Create a variable
Print the value of payStatus.
Try it yourself
fun main() {
val hours = 45
// TODO: Write your code below
// Create a variable payStatus using an if expression
// If hours > 40: create overtime variable and return "Overtime: $overtime extra hours"
// Otherwise: create remaining variable and return "Regular: $remaining hours until overtime"
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic InputPractice on your own: Kotlin playground