0
0
Kotlinprogramming~15 mins

Elvis operator (?:) for default values in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the Elvis Operator (?:) for Default Values in Kotlin
📖 Scenario: Imagine you are building a simple app that greets users. Sometimes, the user's name might not be provided, so you want to use a default greeting instead.
🎯 Goal: You will create a Kotlin program that uses the Elvis operator ?: to provide a default greeting when the user's name is missing.
📋 What You'll Learn
Create a nullable variable for the user's name
Create a default greeting string
Use the Elvis operator ?: to assign a greeting message
Print the final greeting message
💡 Why This Matters
🌍 Real World
Many apps need to handle missing or optional information gracefully, like showing a default name when the user does not provide one.
💼 Career
Understanding how to use the Elvis operator helps you write safer Kotlin code that avoids crashes from null values.
Progress0 / 4 steps
1
Create a nullable variable for the user's name
Create a nullable String variable called userName and set it to null.
Kotlin
Need a hint?

Use String? to make the variable nullable and assign null to it.

2
Create a default greeting string
Create a String variable called defaultGreeting and set it to "Hello, Guest!".
Kotlin
Need a hint?

Just assign the string "Hello, Guest!" to the variable defaultGreeting.

3
Use the Elvis operator to assign a greeting message
Create a String variable called greeting that uses the Elvis operator ?: to assign userName if it is not null, or defaultGreeting if it is null.
Kotlin
Need a hint?

Use userName ?: defaultGreeting to assign greeting.

4
Print the final greeting message
Write a println statement to print the value of greeting.
Kotlin
Need a hint?

Use println(greeting) to show the greeting on the screen.