kotlin

Synopsis

Kotlin is a statically typed programming language that runs on the Java Virtual Machine and also can be compiled to JavaScript source code or use the LLVM compiler infrastructure. It is developed by JetBrains.

Basic

Variables

Print

fun main() {
  println("Hello World")
}

Strings

fun main(args : Array<String>) {
    val name = "Adam"
    val helloName = "Hello, $name"
    val upercaseName = "Hello".uppercase()
}

Booleans

val trueBoolean = true
val falseBoolean = false
val andCondition = trueBoolean && falseBoolean
val orCondition = trueBoolean || falseBoolean

Floats

val intNumber = 10
val doubleNumber = 10.0
val longNumbe = 10L
val floatNum = 10.0F

If Else

Kotlin supports the usual logical conditions from mathematics:

Kotlin has the following conditionals:

val time = 20
if (time < 18) {
  println("Hello")
} else {
  println("Bye")
}
//output - "Bye"

For loop

for (i in 0..5 step 1) 
    {
        print("$i ")
    }
//Will print i from 0 t0 4 (i<5)

While Loop

The while loop loops through a block of code as long as a specified condition is true

var i = 0
while (i < 5) {
  println(i)
  i++
}
//Will print i from 0 t0 4 (i<5)

Do While Loop

The do while loop loops through a block of code atleast once even when the condition is not true

var i = 0
do {
  println(i)
  i++
}while (i < 5)
//Will print i from 0 t0 4 (i<5)

Classes

Classes in Kotlin are declared using the keyword class class Student{ /*...*/ }

Primary Constructor

class Student(val name: String, val age: Int)
val student1 = Student("Peter", 11)

Secondary Constructor

class Student(val name: String) {
    private var age: Int? = null
    constructor(name: String, age: Int) : this(name) {
        this.age = age
    }
}
// Above can be replaced with default params
class Student(val name: String, val age: Int? = null)

Enum Class

enum class Color(val rgb: Int) {
    RED(0xFF0000),
    GREEN(0x00FF00),
    BLUE(0x0000FF)
}

Data Class

data class Student(val name: String, val age: Int)

Functions

Kotlin functions are declared using the fun keyword

fun printStudentName() {
    print("Richa")
}

Parameters & Return Types

fun printStudentName(student: Student) {
    print(student.name)
}

Default Parameters

fun getStudentName(student: Student, intro: String = "Hello,") {
    return "$intro ${student.name}"
}

Collections

A collection is a group of related items

CollectionsSyntax
Listval numbers = listOf(“one”, “two”, “three”, “four”)
Setval numbers = setOf(1, 2, 3, 4)
Mapval numbersMap = mapOf(“key1” to 1, “key2” to 2, “key3” to 3, “key4” to 1)