In this tutorial, we will learn about if expression in Kotlin. In Kotlin “if” is not a keyword(as it was in Java). In Kotlin “if” is an expression and it returns a value. In mean ordinary “If expression” in Kotlin can work just like a ternary operator(condition ? then: else) of Java. Apart from this, we can also use “if-else” as simple blocks the same as other languages(Java or c).
Page Contents
Example Program:
In this example, we will use “if-else” as simple blocks.
fun main(args: Array<String>) {
var num1=20
var num2=10
var max:Int
if (num1 > num2) {
max = num1
} else {
max = num2
}
println("Max is "+max)
}
Example Program:
In this example, we will use “if” as expression.
fun main(args: Array<String>) {
var num1=20
var num2=10
val max = if (num1 > num2) num1 else num2
print("Max is ="+max)
}
Example Program:
It is important “if ” expression can still return value while using as blocks the last statement of the block can be used to return value.
fun main(args: Array<String>) {
var num1=10
var num2=2
val max = if (num1>num2) {
println("num1 is big")
num1
} else {
println("num2 is big")
num2
}
println("Value of max ="+max)
}
Parvesh Sandila is a results-driven tech professional with 8+ years of experience in web and mobile development, leadership, and emerging technologies.
After completing his Master’s in Computer Applications (MCA), he began his journey as a programming mentor, guiding 100+ students and helping them build strong foundations in coding. In 2019, he founded Owlbuddy.com, a platform dedicated to providing free, high-quality programming tutorials for aspiring developers.
He then transitioned into a full-time programmer, where his hands-on expertise and problem-solving skills led him to grow into a Team Lead and Technical Project Manager, successfully delivering scalable web and mobile solutions. Today, he works with advanced technologies such as AI systems, RAG architectures, and modern digital solutions, while also collaborating through a strategic partnership with Technobae (UK) to build next-generation products.
