Kotlin Tutorial (Part 3) — Basic Syntax

Arman Kolahan
2 min readSep 7, 2020

In this article, we start discussing the syntax in Kotlin programming language.

Package and Import

Package declaration

In the first line of each file, the package name should be declared:

package my.demo

It should be mentioned that it is not mandatory matching the package name with the folder name.

Import

The next lines after the package declaration are the imports from other packages, such as classes, top-level functions and properties, functions and properties of an object, and enum constants. Some samples of import syntax:

import org.example.Message
// Message is now accessible without qualification
import org.example.*
// everything in 'org.example' becomes accessible

Functions

The keyword that is used for declarations of functions is fun.

Void Function

A function that is not returning a meaningful value:

fun doSomething() {
println("I am doing something")
}

A void function with input values:

fun printSum(a: Int, b: Int) {
println("sum of $a and $b is ${a + b}")
}

Functions that Return Values

A function that returns a value is like:

fun sum(a: Int, b: Int): Int {
return a + b
}

This type of function needs to have a return keyword in order to return something by calling it.

Variables

Read-only variables

These variables are defined by val keyword that can be assigned once.

val a: Int = 1
a = 2 // ERROR

Reassignable variables

these variables are defined by var keyword.

var a: Int = 1
a = 2

In the next parts of the tutorial, we are going to dive into details of each syntax in Kotlin.

--

--

Arman Kolahan

Experienced frontend engineer & architect with over a decade of expertise in React. Proven leader and team builder. Passionate writer.