Running a Kotlin Program
To run the kotlin program write the code in your favorite edition and save the file with .kt extension. Now to compile the code follow the following command in the terminal:
1 | kotlinc filename.kt -include-runtime -d filename.jar |
This will make a .jar file that is runnable and contain the Kotlin runtime library in it. Now to run the application follow the following command:
1 | java -jar hello.jar |
In Kotlin, the traditional “Hello World” program is very simple. Open a text editor and type the following code:
1 2 3 | fun main() { println("Hello, World!") } |
Save the file with a .kt extension, such as “hello.kt”. Open a terminal and navigate to the directory where you saved the file. To compile the program, type:
1 | kotlinc hello.kt -include-runtime -d hello.jar |
This will create an executable JAR file called “hello.jar”. To run the program, type:
1 | java -jar hello.jar |
You should see the output “Hello, World!” displayed in the terminal.
Basic Syntax:
1 2 3 4 5 6 7 8 9 10 11 | // Single line comments /* Multi line comments Spanning over 3 lines */ /* This is a multi-line comment and it can span * as many lines as you like /* This is a nested comment */ // Another nested comment */ |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | // Keywords // Hard Keywords as as? break class continue do else false for fun if in !in interface is !is null object package return super this throw true try typealias typeof val var when while // Soft keywords by catch constructor delegate dynamic field file finally get import init param property receiver set setparam value where // Modifier Keywords actual abstract annotation companion const crossinline data enum expect external final infix inline inner internal lateinit noinline open operator out override private protected public reified sealed suspend tailrec vararg |
1 2 3 4 | // Variables var x = 123 // Mutable val y = 345 // Immutable ( constant ) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | // Types var name: String = "Zara Ali" var age: Int = 19 // Numbers val a: Int = 10000 val d: Double = 100.00 val f: Float = 100.00f val l: Long = 1000000004 val s: Short = 10 val b: Byte = 1 // Characters val letter: Char 'A' // String val escapedString : String = "I am escaped String!\n" var rawString :String = """This is going to be a multi-line string and will not have any escape sequence"""; // Boolean val A: Boolean = true // defining a variable with true value val B: Boolean = false // defining a variable with false value // Array val numbers: IntArray = intArrayOf(1, 2, 3, 4, 5) // Type conversions toByte() toShort() toInt() toLong() toFloat() toDouble() toChar() |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | // Arithmetic operators + Addition Adds together two values x + y - Subtraction Subtracts one value from another x - y * Multiplication Multiplies two values x * y / Division Divides one value by another x / y % Modulus Returns the division remainder x % y // Relational > greater than x > y < less than x < y >= greater than or equal to x >= y <= less than or equal to x <= y == is equal to x == y != not equal to x != y // Assignment = x = 10 x = 10 += x += 10 x = x - 10 -= x -= 10 x = x - 10 *= x *= 10 x = x * 10 /= x /= 10 x = x / 10 %= x %= 10 x = x % 10 // Unary + unary plus +x - unary minus -x ++ increment by 1 ++x -- decrement by 1 --x ! inverts the value of a boolean !x // Logical && Logical and Returns true if both operands are true x && y || Logical or Returns true if either of the operands is true x || y ! Logical not Reverse the result, returns false if the operand is true !x // Bitwise shl (bits) signed shift left x.shl(y) shr (bits) signed shift right x.shr(y) ushr (bits) unsigned shift right x.ushr(y) and (bits) bitwise and x.and(y) or (bits) bitwise or x.or(y) xor (bits) bitwise xor x.xor(y) inv() bitwise inverse x.inv() |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | // Booleans val x: Int = 40 val y: Int = 20 x > y = true x < y = false x >= y = true x <= y = false x == y = false x != y = true // and & or val x: Boolean = true val y: Boolean = false val z: Boolean = true x.and(y) = false x.or(y) = true x.and(z) = true |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | // Strings val escapedString : String = "I am escaped String!\n" var rawString :String = """This is going to be a multi-line string and will not have any escape sequence"""; // String templates val name : String = "Zara Ali" println("Name - $name") // Using template with variable name println("Name length - ${name.length}") // Using template with expression. // String indexes val name : String = "Zara Ali" println(name[3]) // 'a' name.length = 8 name.count() = 8 name.lastIndex = 7 name.toUpperCase() = "ZARA ALI" name.toLowerCase() = "zara ali" // String concatenation var firstName : String = "Zara " var lastName : String = "Ali" firstName + lastName = "Zara Ali" firstName.plus(lastName) = "Zara Ali" // Trim chars val name : String = "Zara Ali" name.drop(2) = "ra Ali" name.dropLast(2) = "Zara A" // Substring name.indexOf("Ali") m= 5 // Compare var str1 : String = "Apple" var str2 : String = "Apple" var str3 : String = "Orange" str1.compareTo(str2) = 0 str1.compareTo(str3) = 1 // getOrNull() var name : String = "Zara" name.getOrNull(0) = 'Z' name.getOrNull(100) = null |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | // Arrays val fruits = arrayOf("Apple", "Mango", "Banana", "Orange") val fruits = arrayOf<String>("Apple", "Mango", "Banana", "Orange") val num = intArrayOf(1, 2, 3, 4) byteArrayOf() charArrayOf() shortArrayOf() longArrayOf() // Access Elements val fruits = arrayOf<String>("Apple", "Mango", "Banana", "Orange") fruits[3] = "Orange" fruits.get(3) = "Orange" fruits.set(1) = "Mango" fruits.get(1) = "Mango" fruits.size = 4 fruits.isEmpty() == false for( item in fruits ){ println( item ) } "Mango" in fruits == True val distinct = fruits.distinct() fruits.drop(2) // Drop first 2 elements fruits.dropLast() // Drop last element |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | // Ranges for ( num in 1.rangeTo(4) ) { println(num) } for ( num in 1..4 ) { println(num) } for ( num in 4 downTo 1 ) { println(num) } for ( num in 1..10 step 2 ) { println(num) } for ( ch in 'a'..'d' ) { println(ch) } for ( num in (1..5).reversed() ) { println(num) } for ( num in 1 until 5 ) { // Skips last element println(num) } println((5..10).first) println((5..10 step 2).step) println((5..10).reversed().last) // Filter val a = 1..10 val f = a.filter { T -> T % 2 == 0 } // Utility Functions val a = 1..10 println(a.min()) println(a.max()) println(a.sum()) println(a.average()) println(a.count()) |
In Kotlin, a function is defined using the following syntax:
1 2 3 4 | fun functionName(arg1: Type, arg2: Type): ReturnType { // Function body return returnValue } |
For example, to define a function that adds two numbers, you could write:
1 2 3 | fun add(x: Int, y: Int): Int { return x + y } |
You can also use the shorthand syntax for single-expression functions:
1 | fun add(x: Int, y: Int) = x + y |
To call a function, you simply write the function name followed by the arguments in parentheses:
1 | val result = add(2, 3) |
This will set the variable “result” to 5.
If a function does not return a value, its return type is Unit
1 2 3 4 | fun sumTwo(a:Int, b:Int):Unit{ val x = a + b println( x ) } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | // Higher Order functions // Passing a function as a parameter fun main(args: Array<String>) { val result = calculate(4, 5, ::sum) println( result) } fun sum(a: Int, b: Int) = a + b fun calculate(a: Int, b: Int, operation:(Int, Int) -> Int): Int { return operation(a, b) } // Return a function from a function fun main(args: Array<String>) { val func = operation() println( func(4) ) } fun square(x: Int) = x * x fun operation(): (Int) -> Int { return ::square } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // Lambda functions val square = { number: Int -> number * number } val nine = square(3) val that : Int -> Int = { three -> three } val more : (String, Int) -> String = { str, int -> str + int } val noReturn : Int -> Unit = { num -> println(num) } // Class extensions fun extendString(arg: String, num: Int) : String { val another : String.(Int) -> String = { this + it } return arg.another(num) } |
1 2 3 4 5 6 7 | // Inline functions fun main(args: Array<String>) { myFunction({println("Inline function parameter")}) } inline fun myFunction(function:()-> Unit){ // Do Something } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | // if..else if (condition) { // code block A to be executed if condition is true } else { // code block B to be executed if condition is false } val result = if (condition) { // code block A to be executed if condition is true } else { // code block B to be executed if condition is false } val result = if (age > 18) "Adult" else "Minor" if (condition1) { // code block A to be executed if condition1 is true } else if (condition2) { // code block B to be executed if condition2 is true } else { // code block C to be executed if condition1 and condition2 are false } if(condition1) { // code block A to be executed if condition1 is true if( (condition2) { // code block B to be executed if condition2 is true }else{ // code block C to be executed if condition2 is fals } } else { // code block D to be executed if condition1 is false } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | // When val day = 2 val result = when (day) { 1 -> "Monday" 2 -> "Tuesday" 3 -> "Wednesday" 4 -> "Thursday" 5 -> "Friday" 6 -> "Saturday" 7 -> "Sunday" else -> "Invalid day." } when (day) { 1 -> println("Monday") 2 -> println("Tuesday") 3 -> println("Wednesday") 4 -> println("Thursday") 5 -> println("Friday") 6 -> println("Saturday") 7 -> println("Sunday") else -> println("Invalid day.") } when (day) { 1, 2, 3, 4, 5 -> println("Weekday") else -> println("Weekend") } when (day) { in 1..5 -> println("Weekday") else -> println("Weekend") } val x = 20 val y = 10 val z = 10 when (x) { (y+z) -> print("y + z = x = $x") else -> print("Condition is not satisfied") } when (day) { 1 -> { println("First day of the week") println("Monday") } 2 -> { println("Second day of the week") println("Tuesday") } 3 -> { println("Third day of the week") println("Wednesday") } 4 -> println("Thursday") 5 -> println("Friday") 6 -> println("Saturday") 7 -> println("Sunday") else -> println("Invalid day.") } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | // For loops for (item in collection) { // body of loop } for (item in 1..5) { // See definition of range for full set of options println(item) } var fruits = arrayOf("Orange", "Apple", "Mango", "Banana") for (item in fruits) { println(item) } for (index in fruits.indices) { println(fruits[index]) } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | // While while (condition) { // body of the loop } var i = 5; while (i > 0) { println(i) i-- } var i = 5; do{ println(i) i-- } while(i > 0) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | // break and continue // Using break in for loop for (...) { if(test){ break } } // Using break in while loop while (condition) { if(test){ break } } // Using break in do...while loop do { if(test){ break } }while(condition) // Using continue in for loop for (...) { if(test){ continue } } // Using continue in while loop while (condition) { if(test){ continue } } // Using continue in do...while loop do { if(test){ continue } }while(condition) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | // Lists val theList = listOf("one", "two", "three", "four") val theMutableList = mutableListOf("one", "two", "three", "four") theList.toString() val itr = theList.listIterator() while (itr.hasNext()) { println(itr.next()) } for (i in theList.indices) { println(theList[i]) } theList.forEach { println(it) } theList.size if("two" in theList){ println(true) }else{ println(false) } if(theList.contains("two")){ println(true) }else{ println(false) } if(theList.isEmpty()){ println(true) }else{ println(false) } theList.indexOf("two") theList.get(2) val resultList = theList.slice( 2..4) val firstList = listOf("one", "two", "three") val secondList = listOf("four", "five", "six") val resultList = firstList + secondList val firstList = listOf("one", "two", "three") val secondList = listOf("one", "five", "six") val resultList = firstList - secondList val theList = listOf(10, 20, 30, 31, 40, 50, -1, 0) val resultList = theList.filter{ it > 30} val resultList = theList.drop(3) val resultList = theList.groupBy{ it % 3} // => {1=[10, 31, 40], 0=[12, 30, 9, -3, 0]} val resultList = theList.map{ it / 3 } // => [3, 4, 10, 10, 13, 3, -1, 0] val resultList = theList.chunked(3) // => [10, 12, 30], [31, 40, 9], [-3, 0]] val resultList = theList.windowed(3) // => [[10, 12, 30], [12, 30, 31], [30, 31, 40], [31, 40, 9], [40, 9, -3], [9, -3, 0]] val theList = mutableSetOf(10, 20, 30) theList.add(40) theList.remove(10) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | // Sets val theSet = setOf("one", "two", "three", "four") val theMutableSet = mutableSetOf("one", "two", "three", "four") val itr = theSet.asIterable().iterator() while (itr.hasNext()) { println(itr.next()) } for (i in theSet.indices) { println(theSet.elementAt(i)) } theSet.forEach { println(it) } theSet.size if("two" in theSet){ println(true) }else{ println(false) } if(theSet.contains("two")){ println(true) }else{ println(false) } if(theSet.isEmpty()){ println(true) }else{ println(false) } theSet.indexOf("two") theSet.elementAt(2) val firstSet = setOf("one", "two", "three") val secondSet = setOf("one", "four", "five", "six") val resultSet = firstSet + secondSet val firstSet = setOf("one", "two", "three") val secondSet = setOf("one", "five", "six") val resultSet = firstSet - secondSet val theSet = setOf(10, 20, 30, 31, 40, 50, -1, 0) var resultSet = theSet.sorted() var resultSet = theSet.sortedDescending() val resultSet = theSet.filter{ it > 30} val resultSet = theSet.drop(3) val resultSet = theSet.groupBy{ it % 3} val resultSet = theSet.chunked(3) val resultSet = theSet.windowed(3) val theSet = mutableSetOf(10, 20, 30) theSet.add(40) theSet.remove(10) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | // Maps val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4) val theMutableMap = mutableSetOf("one" to 1, "two" to 2, "three" to 3, "four" to 4) val theMap = HashMap<String, Int>() theMap["one"] = 1 theMap["two"] = 2 theMap["three"] = 3 theMap["four"] = 4 val theMap = mapOf(Pair("one", 1), Pair("two", 2), Pair("three", 3)) theMap.entries theMap.keys theMap.values theMap.toString() val itr = theMap.keys.iterator() while (itr.hasNext()) { val key = itr.next() val value = theMap[key] println("${key}=$value") } for ((k, v) in theMap) { println("$k = $v") } theMap.forEach { k, v -> println("Key = $k, Value = $v") } theMap.size == theMap.count() if(theMap.containsKey("two")){ println(true) }else{ println(false) } if(theMap.containsValue("two")){ println(true) }else{ println(false) } if(theMap.isEmpty()){ println(true) }else{ println(false) } theMap.get("two") == theMap["two"] val firstMap = mapOf("one" to 1, "two" to 2, "three" to 3) val secondMap = mapOf("one" to 10, "four" to 4) val resultMap = firstMap + secondMap val theMap = mapOf("one" to 1, "two" to 2, "three" to 3) val theKeyList = listOf("one", "four") val resultMap = theMap - theKeyList theMap.remove( "two") theMap -= listOf("two") ar resultMap = theMap.toSortedMap() var resultMap = theMap.filterValues{ it > 2} var resultMap = theMap.filterKeys{ it == "two"} var resultMap = theMap.filter{ it.key == "two" || it.value == 4} val resultMap = theMap.map{ (k, v) -> "Key is $k, Value is $v" } val theMap = mutableMapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4) theMap.put("four", 4) theMap["five"] = 5 theMap.remove("two") |
Classes
In Kotlin, classes and objects are defined using the following syntax:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | class MyClass { // Class members } class OuterClass{ // Members of Outer Class class NestedClass{ // Members of Nested Class } } class OuterClass{ // Members of Outer Class class inner InnerClass{ // Members of Inner Class } } |
For example, to define a class that represents a person, you could write:
1 2 3 4 5 | class Person(val name: String, var age: Int) { fun sayHello() { println("Hello, my name is $name.") } } |
You can create an instance of a class using the following syntax:
1 | val person = Person("John", 30) |
You can access properties and call methods of the object using the “.” operator:
1 | person.sayHello() |
This will display the output “Hello, my name is John.” in the terminal.
1 2 3 4 5 6 7 8 9 10 11 | // Objects // An object represents a single static instance, and can never have any more or any less than this one instance. object SimpleSingleton { val answer = 42; fun greet(name: String) = "Hello, $name!" } assertEquals(42, SimpleSingleton.answer) assertEquals("Hello, world!", SimpleSingleton.greet("world")) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | // Constructors class Person constructor(val firstName: String, val age: Int) { // class body } class Person (val firstName: String, val age: Int) { // class body } class Person (val _name: String, val _age: Int) { // Member Variables var name: String var age: Int // Initializer Block init { this.name = _name this.age = _age println("Name = $name") println("Age = $age") } } class Person{ // Member Variables var name: String var age: Int // Initializer Block init { } // Secondary Constructor constructor ( _name: String, _age: Int) { this.name = _name this.age = _age println("Name = $name") println("Age = $age") } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | // Inheritance open class ABC { open val count: Int = 0 open fun think () { println("Hey!! i am thinking ") } } // Class Inheritance class BCD: ABC() { // Override a var override val count: Int init{ count = 100 } // Override a function override fun think() { println("I am from Child") } fun displayCount(){ println("Count value is $count") } } fun main(args: Array<String>) { var a = BCD() a.displayCount() } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | // Abstract Classes abstract class Person(_name: String) { var name: String abstract var age: Int // Initializer Block init { this.name = _name } abstract fun setPersonAge(_age:Int) abstract fun getPersonAge():Int fun getPersonName(){ println("Name = $name") } } class Employee(_name: String): Person(_name) { override var age: Int = 0 override fun setPersonAge(_age: Int) { age = _age } override fun getPersonAge():Int { return age } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | // Interfaces interface ExampleInterface { var myVar: Int // abstract property fun absMethod():String // abstract method fun hello() { println("Hello there, Welcome to TutorialsPoint.Com!") } } class InterfaceImp : ExampleInterface { override var myVar: Int = 25 override fun absMethod() = "Happy Learning " } fun main(args: Array<String>) { val obj = InterfaceImp() } |
1 2 3 4 5 6 7 8 9 | // Visibility public private protected internal |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | // Extension fun <class_name>.<method_name>(){ .... function body } fun String.countVowels(): Int{ var vowels = 0 for (i in 0.. this.length - 1) { val ch = this[i] if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') { ++vowels } } return vowels; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | // Data Class data class <Name> ( parameter1, parameter2, ... parameterN ) // e.g data class Book(val name: String, val publisher: String, var reviewScore: Int) // Automatically generated toString() equals() hashCode() copy() componentN() val book = Book("Kotlin", "Tutorials Point", 10) val( name, publisher, reviewScore ) = book // or var name = book.component1() var publisher = book.component1() var reviewScore = book.component1() |
1 2 3 4 5 6 7 8 9 10 | // Sealed Class sealed interface Error sealed class IOError(): Error class FileReadError(val file: File): IOError() class DatabaseError(val source: DataSource): IOError() object RuntimeError : Error |
1 2 3 4 5 6 7 8 9 10 11 12 | // Generics class genericsExample<T>(input:T) { init { println("I am getting called with the value "+input) } } fun main(args: Array<String>) { var objet = genericsExample<String>("JAVA") var objet1 = genericsExample<Int>(10) } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | // Delegation interface Base { fun print() } class BaseImpl(val x: Int) : Base { override fun print() { print(x) } } class Derived(b: Base) : Base by b fun main() { val b = BaseImpl(10) Derived(b).print() } val myVar: String by lazy { "Hello" } fun main(args: Array<String>) { println(myVar +" My dear friend") } |
1 2 3 4 5 6 7 8 9 10 11 12 | // Destructuring data class Student( val a :String,val b: String ){ var name:String = a var subject:String = b } fun main(args: Array<String>) { val s = Student("TutorialsPoint.com","Kotlin") val (name,subject) = s println("You are learning "+subject+" from "+name) } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | // Exception Handling try { // some code } catch (e: SomeException) { // handler } try { // some code } catch (e: SomeException) { // handler } finally { // optional finally block } try { // some code } catch (e1: SomeException) { // handler } catch (e2: SomeOtherException) { // Other handler } finally { // optional finally block } a: Int? = try { input.toInt() } catch (e: NumberFormatException) { null } |