Skip to main content

Kotlin Basic Syntax: Loop and Conditional Control Operator

In this article, we will cover some basic syntax of Kotlin. Like for, dowhile and while loop, if and when control operator, downTo, step, in and its use. These are first and the very basic concept of any programming language.

Using the if control operator in Kotlin


If the conditional operator in Kotlin is similar to the java and it can be used in the same as like into the java only difference as normal is that we don't require ";"  operator at the end of every line.
var a=11
var b=20
if(a < b){
println("$a is less then $b" )
}

Output:-
11 is less then 20

Using the if with else control operator in Kotlin


we can use the traditional if else statement like we use in the java and syntax for this as given below.
println("Enter the number:")
var c = readLine()

var a=c!!.toInt()
var b=20
if(a < b){
println("$a is less then $b" )
}
else{
println("$a is greater then $b")
}

Output:
Enter the number:12
12 is less then 20

Enter the number:21
21 is greater then 20

Using if else like an expression


We can use the if else control statement like an expression.
println("Enter Two Number\b:")
var (a,b) = readLine()!!.split(' ')
var n1:Int=a.toInt()
var n2:Int=b.toInt()

var maxvalue:Int= if(n1>n2) n1 else n2

println("$maxvalue is the Max value from $n1 and $n2")

Output:
Enter Two Number:
45 12
45 is the Max value from 45 and 12

Using case, Switch and when operator into Kotlin


The case is not supported by the Kotlin instead of the case operator we have when statement which does the work like case statement of c language. It will work like switch operator of the Java.
println("Enter a Number from 0 to 9:")
var number= readLine()
when(number!!.toInt()){
0 -> print("You have entered: Zero")
1 -> print("You have entered: One")
2 -> print("You have entered: Two")
3 -> print("You have entered: Three")
4 -> print("You have entered: Four")
5 -> print("You have entered: Five")
6 -> print("You have entered: Six")
7 -> print("You have entered: Seven")
8 -> print("You have entered: Eight")
9 -> print("You have entered: Nine")
else -> print("${number.toInt() } is out of Range")
}

Output:
Enter a Number from 0 to 9:
0
You have entered: Zero

Using "in" operator in Kotlin for checking the value from the range


we can use the "in" operator where we have to validate the number from the range. For example, we have to check whether the given number follow between 1 to 10;
println("Enter a Number for validation:")
var number= readLine()!!.toInt()
if (number in 1..10){
println("$number is within range")
}
else{
println("$number is out of range")
}

Output:
run one with the input value 5
Enter a Number for validation:
5
5 is within range

run two with the input value 11
Enter a Number for validation:
11
11 is out of range

You can see the example that range validation can be done very easily in Kotlin. In other languages, we have to do iteration using for loop but in Kotlin, we can do it by just using the if and in the operator.

Using !in operator to validate the range


println("Enter the index of List:")
var number= readLine()!!.toInt()
var list:List<String> = listOf("Apple","Bananana","Orange")
if (number !in 0..list.lastIndex){
println("$number is out of Index")
}
else{
println("${list.get(number)} is at Index $number")
}

Output
Run1
Enter the index of List:
0
Apple is at Index 0
Run2
Enter the index of List:
-1
-1 is out of Index

Using for loop in Kotlin


There are many ways to use the for loop into the Kotlin, below is the some of the use case and syntax of for loop.

for loop iterates through all type which provides iterator.

A very simple for loop in Kotlin.
for(i in 1..5){
println("$i")
}

Using downTo and Step Operator in Kotlin with for loop


We use the for loop to iterate from some start value to some up value. In Java when we have to do the reverse iteration then we use I-- operator and start the value from the higher value to lower and value and vice versa.  Unlike Java in Kotlin, we have downTo operator using which we can iterator in reverse order.
for(i in 9 downTo 0 ){
print("$i")
}

When we run the above code we will get the below output.
9876543210

i.e. the loop will iterate from 9 to 0 and print all the integer 9 8 7  up to 0, but what if we want to print the number like 9 7 5 3 1 only. If we required printing the output like that then we have to use the step operator.
for(i in 9 downTo 0 step 2){
print("$i")
}

Output:
97531
Process finished with exit code 0

Using for loop with List or array in Kotlin


Iterating with the index of the List.
val list:List<String> =listOf("a","b","c","d")
for (item in list.indices){
print("${list[item]},")
}

Output:
a,b,c,d,
Process finished with exit code 0

or if you want to use the item instead of the index then it is more simple than any other programming language.
val list:List<String> =listOf("a","b","c","d")
for(item in list){
print("$item,")
}

The output of the above code will same as previous code only the implementation part are changed.
a,b,c,d,
Process finished with exit code 0

While loop in Kotlin


The syntax of while and dowhile was same as the java there is no any change in that.
val list:List<String> =listOf("a","b","c","d")
var x=0
while (x<list.size ){
println("is ${list[x]} at Index $x")
x++
}

When we run the above code we will get the following output.
a at Index 0 
b at Index 1
c at Index 2
d at Index 3

Similarly, we can use the do while loop in Kotlin.
val list:List<String> =listOf("a","b","c","d")

var x=0
do{
println("${list[x]} at Index $x" )
x++
}while (x<list.size)

Output:
a at Index 0
b at Index 1
c at Index 2
d at Index 3

Conclusion


In this article, we have tried to present the basic syntax of the Kotlin programming. We can say these are building block if you what to be a good Kotlin developer. We have tried to make all the example as simple as possible but still, if you have any doubt or query you can put your comment below.

 

Comments

Popular posts from this blog

Flutter How to Start Android Activity from Flutter View

Flutter and Dart is an excellent combination for creating the UI, but for accessing the platform-specific service we need to open platform-specific activity. So lets in this article we will explore how to start an android activity and access the service from Flutter View. Create a Project for this Android Activity Flutter View Demo Create a Project From File menu select the New Flutter Project Enter the project name Select the AndroidX support and click on next After the above, we step click on Finish We will have the following project structure created. Create the Second Activity in Android Just go to the android folder and open it in separate windows. We will have the following project structure. Create the Activity Just right-click on the Kotlin folder and create a blank activity from the menu. If you create the activity then you may be required to upgrade the Gradle and do some import. So Just click on update and wait for the project s

Kotlin Parcelable Array Objects Send To Activity

We know that IPC (Inter Process Communication) between the activity is an extremely important part of any application development. We often required that we need to send some data to other activity. For example, we may be required to send an array of data, data could be an Integer, String, Long, Double, Float or any other custom data objects. So, In this example, we are going to learn how to implement the Kotlin Parcelable Array object to send the data from one activity to second activity. What is Parcel? The parcel class is designed as a high-performance IPC transport. A Parcel can contain both flattened data that will be unflattened on the other side of the IPC, and references to live IBinde r objects that will result in the other side receiving a proxy IBinder connected with the original IBinder in the Parcel. Create Kotlin Parcelable Array Objects Parcelable is API for placing the arbitrary objects into the Parcel. In Actual in android app development, Parcelable is an interface

Flutter Theme Creation, Programmatic Way

Flutter and Dart is an excellent combination for creating the mobile app with material design with nice GUI. Its lots of widget which help the developer for creating the app UI very fast with respect to the other language. You may face some problem in starting due to comm, curly brace and semicolon but after some time you will find the way how to work with these all stuff and it becomes very easy for you. But in this article, we are not going to discuss all these. In this article, we will handle a very interesting topic on how to create a custom theme or multiple themes and let's user decide which theme to use. Create a flutter project So let's create a flutter project by selecting the appropriate option from the File menu in android studio or Visual Code. If you are new to Flutter and Dart you can check out our recent post to get started Creating Cross-platform app using flutter . Once your project is created you will get the default counter app and you try running the app in