Question
In Kotlin, is there an equivalent to the following Swift code?
if let a = b.val {
} else {
}
The goal is to safely unwrap a possibly null value, use it when it exists, and run alternative logic when it does not.
Short Answer
By the end of this page, you will understand how Kotlin handles nullable values and how to write the Kotlin equivalent of Swift's if let. You will learn when to use a plain if null check, when to use ?.let { ... }, and how the Elvis operator ?: helps with fallback behavior.
Concept
Kotlin does not have Swift's exact if let syntax, but it solves the same problem through its null-safety system.
In Kotlin, a variable can be either:
- non-nullable: it must always hold a value
- nullable: it may hold a value or
null
For example:
val name: String = "Ada" // cannot be null
val nickname: String? = null // can be null
This matters because Kotlin prevents many null-related runtime errors at compile time. If a value might be null, Kotlin forces you to handle that case explicitly.
Swift's if let means:
- check whether a value exists
- if it does, unwrap it into a non-null local variable
- otherwise, run the
elsebranch
In Kotlin, the most direct equivalent is usually:
if (b.`val` != null) {
val a = b.`val`
// use a
} else {
// handle null
}
Or more idiomatically:
b.`val`?.let { a ->
// use a
} ?: run {
}
Mental Model
Think of a nullable value like a box that may or may not contain an item.
- Swift's
if letsays: "Open the box only if something is inside." - Kotlin says the same thing in a few different ways:
if (box != null): first check whether the box is emptybox?.let { ... }: only perform the action if the box contains somethingbox ?: fallback: if the box is empty, use something else instead
So the core idea is not the exact syntax. The real idea is: handle missing values safely before using them.
Syntax and Examples
1. Direct if null check
This is the clearest equivalent to Swift if let when you want both an if and an else.
val value = b.`val`
if (value != null) {
val a = value
println("Value exists: $a")
} else {
println("Value is null")
}
Here:
valuemay be nullif (value != null)checks for that- inside the
ifblock, Kotlin knowsvalueis non-null
2. Using ?.let
b.`val`?.let { a ->
println("Value exists: $a")
}
This runs the block only if b.val is not null.
3. Using with an -style fallback
Step by Step Execution
Consider this Kotlin example:
val input: String? = "hello"
input?.let { value ->
println("Inside let: $value")
} ?: run {
println("Input was null")
}
Step-by-step
inputis declared asString?, so it may be null.input?.let { ... }means:- if
inputis not null, calllet - if
inputis null, skip the block
- if
- In this case,
inputis"hello", so theletblock runs. - Inside the block,
valueis non-null and equals"hello". - The line
println("Inside let: $value")prints:
Inside let: hello
- Because the left side was not null, the
?: run { ... }part is not used.
Real World Use Cases
API responses
A server may return an optional field:
val email: String? = response.email
email?.let {
sendEmail(it)
} ?: run {
log("No email address available")
}
Android UI updates
A screen may only show some data if it exists:
user.bio?.let {
bioTextView.text = it
} ?: run {
bioTextView.text = "No bio provided"
}
Parsing input
User input may be missing or invalid:
val ageText: String? = readLine()
if (ageText != null) {
println("You entered: $ageText")
} else {
println("No input provided")
}
Configuration values
Apps often use defaults when a setting is absent:
val host = config.host ?: "localhost"
Database fields
Nullable database columns are common:
record.middleName?.let {
println("Middle name: $it")
}
Real Codebase Usage
In real Kotlin projects, developers choose different null-handling styles depending on intent.
1. Guard clauses
When a value is required, developers often return early:
fun process(user: User?) {
val validUser = user ?: return
println(validUser.name)
}
This avoids deep nesting.
2. Validation before work
fun register(email: String?) {
if (email == null) {
println("Email is required")
return
}
println("Registering $email")
}
3. Run code only when data exists
sessionToken?.let {
apiClient.authenticate(it)
}
This pattern is very common for optional values.
4. Default values with Elvis
val pageSize = request.pageSize ?: 20
5. Error handling with
Common Mistakes
1. Trying to use a nullable value directly
Broken code:
val name: String? = null
println(name.length)
Problem:
namemay be null, so Kotlin does not allow direct access tolength
Fix:
println(name?.length)
or
if (name != null) {
println(name.length)
}
2. Using let when a simple if is clearer
This works, but can be harder to read:
value?.let {
println(it)
} ?: run {
println("null")
}
Sometimes this is clearer:
if (value != null) {
println(value)
} else {
println("null")
}
Choose readability over cleverness.
3. Overusing
Comparisons
| Approach | Best for | Has else branch? | Notes |
|---|---|---|---|
if (x != null) | Clear branching logic | Yes | Most direct equivalent to Swift if let |
x?.let { ... } | Run code only if value exists | No | Concise for non-null path only |
x?.let { ... } ?: run { ... } | Expression-style null/non-null branching | Yes | Compact but can be less readable for beginners |
val y = x ?: fallback | Default values | Not exactly | Best when you need a replacement value |
Cheat Sheet
Quick reference
Nullable type
val name: String? = null
Check for null
if (name != null) {
println(name)
} else {
println("null")
}
Safe call
println(name?.length)
let
name?.let {
println(it)
}
let with fallback
name?.let {
println(it)
} ?: run {
println("null")
}
Elvis operator
val displayName = name ?: "Guest"
Throw if missing
val id = inputId ?: throw IllegalArgumentException()
FAQ
Is let the same as Swift if let in Kotlin?
Not exactly, but it solves a similar problem. ?.let { ... } runs code only when the value is not null.
What is the closest direct equivalent to Swift if let ... else in Kotlin?
Usually:
if (value != null) {
// use value
} else {
// null case
}
Should I use if or let in Kotlin for null checks?
Use if when you want clear branching. Use let when you want a concise action only for the non-null case.
What does ?: mean in Kotlin?
It is the Elvis operator. It provides a fallback when the value on the left is null.
Why does Kotlin use String??
The ? means the type is nullable. Without it, the variable cannot hold null.
Mini Project
Description
Build a small Kotlin program that reads an optional username and prints one message if the username exists and a different message if it is null. This demonstrates the Kotlin equivalent of Swift's if let in a practical way.
Goal
Practice handling nullable values using both if null checks and ?.let with a fallback branch.
Requirements
- Create a nullable
Stringvariable for a username. - Print a welcome message when the username is not null.
- Print a guest message when the username is null.
- Show one solution using
ifand another using?.letwith?: run. - Keep the program valid Kotlin and easy to read.
Keep learning
Related questions
Accessing Kotlin Extension Functions from Java
Learn how Kotlin extension functions are compiled and how to call them correctly from Java with clear examples and common pitfalls.
Android AlarmManager Example: Scheduling Tasks with AlarmManager
Learn how to use Android AlarmManager to schedule tasks, set alarms, and handle broadcasts with a simple beginner example.
Android Foreground Service Notification Channels in Kotlin
Learn why startForeground fails on Android 8.1 and how to create a valid notification channel for foreground services in Kotlin.