Updated April 7, 2023
Introduction to Kotlin switch
The kotlin switch is one of the statements that can be used to declare the block in the code but now “when” keyword used instead of the switch block the expression also used to validate the conditions it also satisfied and applied with some other similar data types that can be instead of having a vast or big set of code is used for the conditional statement with the help of switch statement used to avoid with other conditional statements the when a keyword is more ever similar to the switch case statement like other programming languages.
Syntax
In kotlin language have many default classes, methods, and other default variables used to implement the application in both UI and backend logic. The switch is one of the features and it is a loop case statement to iterate the values but now kotlin uses when keywords instead of switch.
fun main(args:Array<String>)
{
val vars;
when(vars)
{
---some logic and conditional statement codes----
}
}
The above codes are the basic syntax for using the when keyword instead of switch blocks in the kotlin language. The looping and other conditional statements are evaluated and validated by the programmer.
How does Switch work in Kotlin?
The switch is one of the statements that can be used to declare and construct the loops to iterate the user input values. In kotlin language when a keyword can be used to declare the expression or statement while using that it can also satisfied with the branch’s value becoming the value of all the expressions. Each case statement is used with the individual branches the values are ignored and it is used with the default cases like java switch statement the else is the mandatory one when it used as the expression. If we used when keywords without any expressions it will act as the if-else chain blocks the boolean conditions and expressions also validated with specified logics. It is helpful when the user has n number of choices that want to be performed with the different tasks for each other choices. Mainly the switch statement allows for testing the variable in an equality manner against the list of values. Each value is defined and it is known as the cases generally the switch statement used break keyword for breaking the lines but is not a required manner it seems to be optional. Instead of switch when keyword used same case statements but here break keyword is not used and also we can use else statement if it is required.
Examples of Kotlin switch
Given below are the examples of Kotlin switch:
Example #1
Code:
package one;
import java.util.*
fun main() {
var str1: String? = null
var str2: String? = "Welcome To My Domain is the first example that relates to the Kotlin Switch statement"
var strlen1: Int = if (str1 != null) str1.length else -1
var strlen2: Int = if (str2 != null) str2.length else -1
println("Length of str1 is ${strlen1}")
println("Length of str2 is ${strlen2}")
println("Enter the Color code from these jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec")
val vars = readLine()
val vars2 = when (vars) {
"jan" -> "January"
"feb" -> "February"
"mar" -> "March"
"apr" -> "April"
"may" -> "May"
"jun" -> "June"
"jul" -> "July"
"aug" -> "August"
"sep" -> "September"
"oct" -> "October"
"nov" -> "November"
"dec" -> "December"
else -> "Please enter your inputs?"
}
println("$vars2")
println("Thank you users for spenting the time with our application")
val sc = Scanner(System.`in`)
print("Enter the numbers: ")
val inp1 = sc.nextDouble()
val inp2 = sc.nextDouble()
val inp3 = sc.nextDouble()
val inp4 = sc.nextDouble()
val inp5 = sc.nextDouble()
print("Please choose the operator to perform the mathematical operations (+, -, *, /): ")
val opn = sc.next()[0]
val out: Double
when (opn) {
'+' -> out = inp1 + inp2 + inp3 + inp4 + inp5
'-' -> out = inp1 - inp2 - inp3 - inp4 - inp5
'*' -> out = inp1 * inp2 * inp3 * inp4 * inp5
'/' -> out = inp1/ inp2
else -> {
System. out.printf("The operations are failed because due to the wrong inputs")
return
}
}
System.out.printf("%.1f %c %.1f = %.1f", inp1, opn, inp2, out)
}
Sample Output:
In the above example, we calculate the mathematical operations by using the when statement.
Example #2
Code:
package one;
import java.util.Scanner;
fun demo(new: Any) = when (new) {
is String -> new.startsWith("Welcome To My Domain its the first example that relates to the Kotlin switch")
else -> false
}
fun main(args: Array<String>) {
var str = Scanner(System.`in`)
print("Please enter your brand:")
var bndName = str.nextInt()
var out = when(bndName){
1->"Adidas"
2->"Bata"
3->"ASICS"
4->"MK"
5->"Sleeves"
6->"Jockey"
7->"Nike"
8->"Adidas"
9->"Skechers"
10->"Fila"
11->"Kering(PUMA)"
12->"The Shoe Rack"
13->"New Balance"
else -> {
println("Your brand is not listed here")
}
}
println(out)
var new = "Welcome To My Domain its the first example that relates to the Kotlin switch concept"
var res = demo(new)
if(res) {
println("Yes, Your brand is listed Welcome To My Domain its the first example that relates to the Kotlin switch")
}
else {
println("No, Sorry your brand is not listed here Kindly try with one more and please stay with our application and spent your valuable time for us thanks")
}
}
Sample Output:
In the second example we used to check the brand conditions with corresponding values with the help of the when statement.
Example #3
Code:
package one;
import java.util.Scanner;
enum class Textile {
CHENNAISILKS, POTHYS, SRAVANASTORES, MJS, SPJ, SIVATEXTILE
}
fun main() {
val result = Textile.POTHYS
when (result) {
Textile.CHENNAISILKS -> println("It is Chennai Silks")
Textile.POTHYS -> println("It is POTHYS")
Textile.SRAVANASTORES -> println("It is Saravana Stores")
Textile.MJS -> println("It is MJS")
Textile.SPJ -> println("It is SPJ")
Textile.SIVATEXTILE -> println("It is Siva Textile")
}
}
Sample Output:
In the final example, we used enum and we can create the reference of the enum and we called and iterate the enum values using the when statement.
Conclusion
In the kotlin language, we used many different concepts and features to implement the mobile with web-based applications. Like that the Switch is one of the looping and conditional expressions to validate the input data from both front and backend. We can use “when” keyword to achieve these switch case logics in the kotlin application.
Recommended Articles
This is a guide to the Kotlin switch. Here we discuss the introduction, syntax, and working of switch in Kotlin along with different examples and code implementation. You may also have a look at the following articles to learn more –