Introduction
This blog will introduce a famous and vital Android development language named Kotlin. It is an open-source language developed by JetBrains.
You will get familiar with the basic syntax of Kotlin and learn fundamental concepts like variables, functions, and many more concepts in Kotlin. Towards the end of the blog, you will be able to write your first Hello World program.
Basic syntax
In this section, we will look at the basic syntax of Kotlin and a lot of related examples to understand its syntax in depth.
The main() function
The main() function is the most important function of a Kotlin application. It acts as the entry point for any Kotlin application. The following code snippet depicts an example of the main function.
fun main() {
println("Inside main function")
}
Note: As illustrated above, the println() function is used to print messages to the standard output. It also adds a line break after printing the output.
Variables
Variables are abstract storage locations used to store data value inside them. There are two types of keywords used to define variables.
Read-only local variables are defined using the keyword val.
fun main() {
val x: Int = 10 // immediate assignment
println("The value of x is $x")
val y = 4 // `Int` type is inferred
println("The value of y is $y")
val z: Int // Type required when no initializer is provided
z = 3 // deferred assignment
println("The value of z is $z")
}
Output:
The value of x is 10
The value of y is 4
The value of z is 3
Variables that can be reassigned are defined using the var keyword.
fun main() {
var y = 10 // `Int` type is inferred
y -= 1 // Reassigning the value of variable named y
println("The value of y is $y")
}
Output:
The value of y is 9
Functions
A function is a logical unit of code that performs a specific task. Functions make the code more modular. Functions can be in-built (i.e., imported from some library) or user-defined. sqrt(), println(), readLine() are examples of standard library functions of Kotlin. Examples of user-defined functions are as follows:
A function with two Int parameters and Int return type:
fun sum(x: Int, y: Int): Int {
return x + y
}
fun main() {
var res = sum(10,20)
println("Sum is $res")
}
Output:
Sum is 30
A user-defined function named employee() having different types of parameters-
fun employee(name: String , salary: Int , rating: Char) {
println("Name of the employee is : $name")
println("Salary of the employee is: $salary")
println("Rating of the employee is: $rating")
}
fun main() {
employee("Ninja",1200000,'A')
}
Output
Name of the employee is : Ninja
Salary of the employee is: 1200000
Rating of the employee is: A