Ternary With If Expression
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 27 of 93.
Many programming languages have a ternary operator: a shorthand way to choose between two values based on a condition. In Kotlin, there's no separate ternary operator because if itself can be used as an expression that returns a value.
Instead of writing condition ? valueIfTrue : valueIfFalse like in other languages, Kotlin uses if directly:
fun main() {
val age = 20
val status = if (age >= 18) "Adult" else "Minor"
println(status) // Prints: Adult
}The if expression evaluates the condition and returns one of two values. If the condition is true, it returns the value after if. If false, it returns the value after else.
This result can be stored in a variable or used directly.
fun main() {
val score = 85
println(if (score >= 60) "Pass" else "Fail") // Prints: Pass
}This compact syntax is perfect for simple either-or decisions where you need to assign or return a value based on a single condition.
Challenge
EasyYou are provided with the following variables:
val temperature = 28
val isSunny = trueCreate a variable activity that uses an if expression to choose between two activities based on the weather conditions.
Logic:
- If the temperature is greater than 25 and it is sunny, assign
"Go to the beach" - Otherwise, assign
"Stay indoors"
Use the compact if expression syntax (single line) to assign the value directly to activity.
Print the value of activity.
Try it yourself
fun main() {
val temperature = 28
val isSunny = true
// TODO: Write your code below
// Create a variable 'activity' using an if expression (single line)
// If temperature > 25 AND isSunny, assign "Go to the beach"
// Otherwise, assign "Stay indoors"
// Print the activity
// println(activity)
}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