In this tutorial, we will learn about when operator in Kotlin. When operator is work same as Switch statement of Java. In Kotlin when operator uses to match an argument with all the branches until it finds a satisfying condition in a branch. After finding satisfying condition it runs all statements inside the scope of that branch. Follow the given example to understand when operator.
Page Contents
Example Program:
fun main(args: Array<String>) {
val num:Int = 2
when (num) {
1 -> print("num is = 1")
2 -> print("num is = 2")
else -> {
print("Out of range")
}
}
}
We when operator we can combine multiple branches using comma. check the following example.
Example Program:
fun main(args: Array<String>) {
val num:Int = 8
when (num) {
1,2,3,4,5 -> print("num is in first range")
6,7,8,9,10 -> print("num is in second range")
else -> {
print("Out of range")
}
}
We can also use in to check the particular value in a range or not.
Example Program:
fun main(args: Array<String>) {
val num:Int = 12
when (num) {
in 1..10 -> print("num is in first range")
in 10..20 -> print("num is in second range")
else -> {
print("Out of range")
}
}
}
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.
