Start to learn Kotlin as Beginner

Kundan Kumar
6 min readJun 1, 2020
Photo: exaud-kotlin-action

I finished OPEN CLASSROOM Kotlin’s course, its really good for the beginner and its free. I am sharing here what I learned.

Kotlin developed by JetBrains to address the limitations it encountered with Java during the development of its various products. Kotlin supports object-oriented programming and functional programming. Kotlin is an open-source, supports most IDEs, and works on most current Java platforms.

1. Declaring and initialize variables:

Declaring a variable in Kotlin is a little different from Java. You can declare a variable in Kotlin using var or the val keyword:

  • var: The variable declared using var keyword is mutable. This means you can change the value of a variable after it is initialized.
  • val: The variable declared using val keyword is immutable. This is equivalent to the final keyword in Java. This means you cannot change the value of a variable once it is initialized. A val variable must be initialized in the same block of code in which it was declared
val name: String = "Kundan "
val age: Int = 26
val isDeveloper: Boolean = true
var developerType: String = "Android Developer"

Kotlin does not require you to indicate the type of a variable at the time of declaration. You can also initialize the above variables like below

val name = "Kundan "
val age = 26
val isDeveloper = true
var developerType = "Android Developer"

Variables in Kotlin are non-nullable by default. If you want a variable to hold a null value, you have to declare that it can do so. To allow null values in Kotlin append a question mark(?) to the variable type’s declaration:

var message: String? = "Hello Kundan, how are you "

If you don’t want to initialize variable immediately after declaring it, instead wait until little later in code. So, you can use the keyword lateinit for late initialization:

class User {private var lateinit name: Stringfun initialize(username: String) {
this.name = username
}
}

2. Create Function:

Function in Kotlin declared using fun keyword. Now, create a function that returns the smaller of the values of two variables passed as parameters:

minOf function in Kotlin

In Kotlin all functions return a value even if no return type is specified. For example:

fun printMessage(message: String) {
println(message)
}

In the above example, function printMessage(message: String) return Unit value, which is the default type created by Kotlin. Unit similar to void in Java.

A function is not required to have a body , and may contains only an expression. This is also called single-expression function. For example:

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

Explicitly declaring the return type is optional when this can inferred by the compiler:

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

3. Class:

The class keyword used to declare a class in Kotlin, followed by the name of class. The parentheses, right after the class name is known as primary constructor. Class properties can be declared in the primary constructor.

Class in Kotlin

In Kotlin, the visibility of a class is set to public by default. There are four main visibility modifiers for the members(variables, functions etc.):

  • public: A member that is declared public will be visible everywhere
  • private: A member that is declared private will only be visible inside the class which it is declared.
  • internal: A member that is declared internal will be visible to any client inside the same module.
  • protected: A member that is declared private will only be visible inside the class and in its sub-classes.

In Kotlin you don’t need new keyword to instantiate a class as an object:

val user = User("Kundan", "Kotlindemo", 26)

In Kotlin setters and getters are auto-generated in the code.

  • val: The val keyword placed before the name of a property in the class constructor tells Kotlin to automatically generate a getter.
  • var: The val keyword placed before the name of a property in the class constructor tells Kotlin to automatically generate a getter and a setter.

4. If and when statements:

  • If: In Kotlin if is an expression and can return a value. Kotlin eliminates the use of ternary operator by using if else as expressions.
val max = if(a > b) a else b

If branches can be block and the last expression is the value of a block:

val max = if(a > b) {
println("a is greater than b")
println("a is the max value")
a
}
else {
println("b is greater than a")
println("b is the max value")
b
}
  • when: when in Kotlin is similar to switch in other languages. when matches its argument against all branches sequentially until some branch condition is satisfied.
var response = 403when(response) {
200 -> println("OK")
401 -> println("UNAUTHORIZED")
403 -> println("FORBIDDEN")
404 -> println("NOT FOUND")
else -> println("UNKNOWN")
}

5. Iterate using loops:

  • for loop: In Kotlin, the for loop used in the form: <item> in <elements>. For example iterate over a range of numbers, use ranges
for(i in 1..8) {
println("item: $i")
}

The step keyword in a for loop is used to skip iterations. For example:

for(i in 1..8 step 2) {
println("item: $i")
}

In the above example used step keyword to skip one item, in order to directly access item i+2.

  • while loop: while and do..while loop work exact same as while in Java.
//while loop
var a = 0
while(a < 6) {
println("Iteration count: $a")
a++
}
//do..while loop
var a = 0
do {
println("Iteration count: $a")
a++
}while(a < 6)

6. Collection:

A collection usually contains a number of objects of the same type. In Kotlin collections are categories into two types: Immutable and Mutable.

  • Immutable: It only support read functionalities and can not be modified its elements. Kotlin immutable collection generic methods are:

listOf: Allow you to create an ordered and immutable list of elements.

val listOfNames = listOf("Kundan", "Iti", "Kajal", "Koyal")
listOfNames[1] = "Priti" //Error: list is immutable

setOf: Allow you to create an unordered and immutable list of elements.

val setOfNames = setOf("Kundan", "Iti", "Kajal", "Koyal")
setOfNames.add("Priti") //Error: set is immutable

mapOf: Allow you to create immutable list of key-value pairs.

val mapOfNames = mapOf("x" to "Iti","c" to "Kajal","f" to "Koyal")
mapOfNames[key] = "value" //Error: map is immutable

7. Extension Function:

In Kotlin the extension function use to extend the behavior of a class, that will be perceived as belonging to the class itself. For example you can use extensions to add the greetMessage() method inside the String class.

fun String.greetMessage() = println("Welcome $name")

To declare an extension function, begin with the keyword fun. Then write the receiver type followed by dot and the name of function you want to create.

Summary

  • You can declare a variable in Kotlin using var or the val keyword.
  • Function in Kotlin declared using fun keyword. In Kotlin all functions return a value even if no return type is specified.
  • In Kotlin if is an expression and can return a value.
  • when in Kotlin is similar to switch in other languages.
  • In Kotlin, the for loop used in the form: <item> in <elements>.
  • In Kotlin collections are categories into two types: Immutable and Mutable.

Have any questions or thoughts? Find me on twitter

--

--

Kundan Kumar

Passionate software engineer with a desire to learn and grow.