Everything You need to know about Kotlin as a Beginner(Basic types, Control flows, Return and Jumps, Functions)

Geno Tech
8 min readJan 10, 2021

In this series of article, I will quickly guide you how to become an expert in Kotlin. Kotlin is a programming language which we can mainly use to replace our java classes when we are developing our android mobile applications. It was introduced by google in 2017 at Google I/O.

Kotlin is an expressive and concise programming language that reduces common code errors and easily integrates into existing apps. If you’re looking to build an Android app, we recommend starting with Kotlin to take advantage of its best-in-class features.

If you are a android developer with java, it is easy to adopt to Kotlin. This quick guide will help you to get a clean start or refresh your knowledge in Kotlin programming language. let’s begin the journey. It’s so simple and easy !!!.

List of Contents

  1. Hello World
  2. Basic Types : Double, Float. Long, Int, Short, Byte
  3. Basic Types : String, Char, Array
  4. Control Flow : If, When, For, While
  5. Returns and Jumps : break, continue
  6. Functions in kotlin : basic, infix, recursive

1. Hello World

First of all we need to builds and run our first application successfully. I am creating the Kotiln console application in IntelliJ IDE. You can use any Kotlin supported IDE on your PC. Initially The program will automatically generate the main.kt file containing with main function. Here, I am showing you every code snippets as follows.

fun main(args: Array<String>) {
println("Hello World!")
}

2. Basic Types : Double, Float. Long, Int, Short, Byte

In programming, there have common variable types to use. It is a must to know how to handle these basic variable types mainly on how we store and how we use those variable types such as integer, float, double etc.

Basically we define a variable using var keyword as follows:

var i: Int = 3;
var d: Double = 3.128;
var f: Float = 3.128F;
var l: Long = 3124_72819_728191; // Here the underscores will not serve and give 312472819728191
var s: Short = 14;
var b: Byte = 2;

println("Integer : $i");
println("Double : $d");
println("Float : $f");
println("Long : $l");
println("Short : $s");
println("Byte : $b")

Here, you can see how print something on the console as well, The print method is getting a string as a parameter and need to use $ sign before print an any variable. Also you no need to put semicolons like in java.That’s really Cool !!!

Another keyword is val, You can assign it for one time which means it’s a constant value once it assigned. therefore the second time you cannot assign it, will give you an error.

val i: Int = 3;
// You cannot assign again for i

As given below, Nullable values we can initialize. But remember that, you need to initialize the variable before use it.

val aNullableInt: Int?
aNullableInt = 43
// Remember you need to initialize it before use it.
print("aNullableInt : $aNullableInt");

Then you can casting two variables easily like this,

val anInt: Int? = 1673;
val aFloat: Float? = anInt?.toFloat()
print("Int is casting to Float : $aFloat");
val anFloat: Float = "1673.56".toFloat()
print("String is converted into Float : $anFloat")

// Output
Int is casting to Float : 1673.0
String is converted into Float : 1673.56

That’s all basics you need to know about variables in Kotlin and how they are using.

3. Basic Types : String, Char, Array

Kotlin has basic variable types you required to know and how we store and how we use different types of variables such as string, char, Array.

  • Char

Char variable is representing a single character, any Unicode character:

//  Characters or char
val c: Char = 'C' // You must declare it in single quote
println("Char variable example: $c")

val dollar: Char = '\u0024' // You must declare it in single quote
print("Char dollar Sign example: $dollar")

// Output
Char variable exapmle: C
Char dollar Sign exapmle: $
  • String

Typically you know, A string is represents a array of single characters.

//  String
val s = "Kotlin Tutorial" // You must declare it in double quote
println("This $s will help you !!!")


// Output
This Kotlin Tutorial will help you !!!
  • Arrays

Arrays are storing and manipulating a sets of elements which are in single variable type. Following example shows you, how declare, initialize and utilized a String array in Kotlin.

//  Arrays in Kotlin - String Array
val sArray: Array<String> = arrayOf("William","James","Harper","Mason","Evelyn","Ella")
println("The example of String Array in Kotlin.")
println("Array Size : ${sArray.size}")
print("Elements of Array : ")
for (element in sArray){
print(element)
print(" ")
}

// Output
Array Size : 6
Elements of Array : William James Harper Mason Evelyn Ella

In that way you can declare, initialize and use an Int Array in Kotlin.

//  Arrays in Kotlin - Int Arrayval iArray: Array<Int> = Array<Int>(4) { a -> 2 * a }
// { i -> 2 * i } is an anonymous function
// Also in this is an another possible way of create an int Array
// val exArray : IntArray = intArrayOf(1,2,3,4);
println("The example of Int Array in Kotlin.")
println("Array Size : ${iArray.size}")
print("Elements of Array : ")
for (element in iArray){
print(element)
print(" ")
}

// Output
Array Size : 4
Elements of Array : 0 2 4 6

4. Control Flow : If, When, For, While

Control flows are important in every programming languages. The way how you can use each of those in Kotlin discussed below. Here the when is a new type of control flow. The other if, for, while control flows should familiar with you and have a knowledge how they works.

  • if/Else statements in Kotlin
//  If / Else Statements in Kotlin

var a: Double = 1.2
var b: Double = 0.1

if(a >= b){
println("a is greater or equal b")
}else{
println("a is less than b")
}


// Output
a is greater or equal b
  • when statements in Kotlin

when in Kotlin is same as switch/case in other languages. Here the way we use it.

//  "when" Statement in Kotlin (Same logic in kotlin)
var c: Char = 'a'
var result: String = when(c){
'a' -> "First character of the alphabet"
'b' -> "Second character of the alphabet"
'c' -> "Third character of the alphabet"
else -> "Other character"
}
print("$c : $result")


// Output
a : First character of the alphabet

You need to remember, the else is same as default in switch/cases in the above scenario. You cannot left the else in the when statement.

The following function is an another example of when :

//  "when" Statement use as a function
fun checkNumber(input: Int) = when(input){
0 ->{
print("This is zero")
}
1,2 -> {
print("This is one or two")
}
in 3..10 -> print("This is between 3 to 10")
else -> print("Any other")
}

checkNumber(5)

// Output
This is between 3 to 10
  • for loop statements in Kotlin

for loops are using to re-run the same code block from start to end which we defined. Also we can use it for many reasons such as read an elements of an array etc. Here the example how we can use for loops.

//  For Loop
val numArray : IntArray = intArrayOf(1,2,3,4,5,6,7,8)

print("Numbers of Array : ")
for(number in numArray){
print("$number ");
}
println()

println("Numbers of Array with indices : ")
for(index in numArray.indices){
println("Value at index $index is ${numArray[index]}")
}

println("Values of Array and indices as pairs : ")
for((index,value) in numArray.withIndex()){
println("Value at index $index is $value")
}

// Output
Numbers of Array : 1 2 3 4 5 6 7 8
Numbers of Array with indices :
Value at index 0 is 1
Value at index 1 is 2
Value at index 2 is 3
Value at index 3 is 4
Value at index 4 is 5
Value at index 5 is 6
Value at index 6 is 7
Value at index 7 is 8
Values of Array and indices as pairs :
Value at index 0 is 1
Value at index 1 is 2
Value at index 2 is 3
Value at index 3 is 4
Value at index 4 is 5
Value at index 5 is 6
Value at index 6 is 7
Value at index 7 is 8
  • while statements in Kotlin
//  while Loop
var x: Int = 5
while(x > 0){
println("x is $x")
x--
}

// Output
x is 5
x is 4
x is 3
x is 2
x is 1

5. Returns and Jumps : break, continue

When we are using control flows, these syntax can use for different purposes.

  • Break — exit for the loop
//  "Break" use in control flows
var numbers:Array<Int> = arrayOf(1,2,3,4,5,6,7,8)
for(eachInt in numbers){
print("$eachInt ")
if(eachInt == 4){
break
}
}

// Output
1 2 3 4
  • Continue — continue to next step of the loop without executing the rest.
//  "Continue" use in control flows
var numbers:Array<Int> = arrayOf(1,2,3,4,5,6,7,8)
for(eachInt in numbers){

if(eachInt == 4){
continue
}
print("$eachInt ")
}

// Output
1 2 3 5 6 7 8
  • Use labels with break when executing two or more for loops
//  More with "Break" : break use inside two loops
lable1@ for(i in 1..5) {
lable2@for (j in 1..5) {
if (i == 2 && j == 2) {
break@lable1
}
println("$i and $j")
}
}
// Output
1 and 1
1 and 2
1 and 3
1 and 4
1 and 5
2 and 1

6. Functions

Functions are the stored set of codes with our program which we can use wherever we want. And Here we discuss how functions implement and use in kotlin.

fun addTwoInts(x:Int, y:Int): Int{
return x + y;
}

println("Adding Two Numbers : ${addTwoInts(3, 5)}");

// Output
Add Two Numbers : 8

If the function is a one line, do not need to put open and close brackets anymore.

fun addTwoInts(x:Int, y:Int): Int = x + y

This is an another example of functions,

fun areaofRectangle(height:Double, width:Double): Double = height + width

println("Area of the Rectangle is : ${areaofRectangle(3.0, 5.0)}");

// Output
Area of the Rectangle is : 8.0

If you want to create a function without a return value, other languages use the keyword void, but Kotlin used the Unit keyword to represent the current function return nothing. This is an example :

fun greetingofTheDay(person: String?, period:String) : Unit{
if(person != null) {
println("Good $period $person !!!")
}else{
println("Good $period !!!")
}
}

greetingofTheDay(null, "Morning") // Here you can pass null values using ? after the parameter at the function
greetingofTheDay("Alan", "Morning")

// Output
Good Morning !!!
Good Morning Alan !!!

Then if you want to pass number of parameters without knowing how many, you can do it using vararg :

// Passing unknown number of parameters
fun functionofInt(vararg intParams: Int){
for(eachItem in intParams){
println("each params : $eachItem")
}
}

functionofInt(1,2,3,4,5,6,7,8);

// Output
each params : 1
each params : 2
each params : 3
each params : 4
each params : 5
each params : 6
each params : 7
each params : 8

Then you need to know about about some especial function types in Kotlin.

  • Infix Notation

This type of function has only one parameter and we can define what do want to do inside it.

// Infix Notation
infix fun Int.plus(x: Int):Int{
return this + x
}

print("The addition of 2 and 4 = ${2 plus 4}");

// Output
The addition of 2 and 4 = 6
  • Recursive Function
// Recursive Function
tailrec fun factorial(n: Long = 1):Long{
if(n == 1L){
return 1
}else{
return n * factorial(n-1);
}
}

print("Factorial value of 5 is = ${factorial(5L)}");

// Output
Factorial value of 5 is = 120

Conclusion

This is the end of the first chapter of Kotlin. We will meet with OOP principles, Collections and other Kotlin stories for intermediates. Please feel free to comment any question, you have faced with this story in the response section below.
Happy Coding !!!!
Found this post useful? Kindly tap the 👏 button below! :)

--

--

Geno Tech

Software Development | Data Science | AI — We write rich & meaningful content on development, technology, digital transformation & life lessons.