Kotlin Cheatsheet
Kotlin Cheatsheet
Kotlin Cheatsheet
1 fun main() {
2 println("Hello World!")
3 }
Variables
val -> read-only or assigned-once
var -> mutable
Functions
// default arguments
// you can omit the name and one of the arguments
// if default values as given to the parameter in the function
1 aboutYou("Sriram")
// if is an expression in kotlin
1 val max = if ( a > b ) a else b
// when in kotlin
1 when (color) {
2 "blue" -> println("cold")
3 "orange" -> println("mild")
4 else -> println("hot")
5 }
// for loop
1 val list = listOf("a", "b", "c", "d", "e")
2 for (i in list) {
3 println(s)
4 }
1 for (i in 1..9) {
2 println(i)
3 }
1 for (i in "abcdefg") {
2 println(i)
3 }
1 println("a" in "abcdef")
// not in a range
1 println(6 !in listOf(1,2,3,4,5))
// in as when-condition
// different ranges
Exceptions
// try is an expression
Calling Extensions
1 class A {
2 fun foo() = 1
3 }
4
5 fun A.foo() = 2
6 // warning: Extension is shadowed by a member
7
8 A().foo() // returns 1
1 class A {
2 fun foo() = 1
3 }
4
5 fun A.foo(i: Int) = i * 2
6 // warning: Extension is shadowed by a member
7
8 A().foo(2) // returns 4
Nullability
Nullable types
Lambdas
// lambda syntax
1 val n = mutableListOf(1,2,3,4,5,6,7,8,9,10)
2
3 val m = n.filter({i -> i % 2 ==0 })
4
// Multi-line lambda
1 val m = n.filter {
2 println("processing $it")
3 it % 2 ==0 // last expression is the result
4 }
// map
// it converts every element in the list by
// the passed expression in the lambda
1 listOf(1,2,3,4).map { it * it } // [1, 4, 9, 16]
// any
// it returns boolean value, true if any one element passes the condition
1 listOf(1,2,3,4).any { it % 2 == 0 } // true
// all
// it returns boolean value, true if all of the element passes the condition
1 listOf(1,2,3,4).all { it % 2 == 0 } // false
// none
// it returns boolean value, true if none of the element passes the condition
1 listOf(1,2,3,4).none { it % 2 == 0 } // false
// find
// it returns the first element if passes the condition or returns null
1 listOf(1,2,3,4).find { it % 2 == 0 } // false
// count
// it returns the count of the elements
// if passes the condition or returns null
1 listOf(1,2,3,4).find { it % 2 == 0 } // false
Function Types
// we can assign function type to a variable which has lambda
// we define the parameter and return type
1 val sum: (Int, Int) -> Int = {x, y -> x + y}
// return keyword returns from the function marked with fun keyword
1 fun main() {
2 val nums = mutableListOf(1,2,3,4,5,6)
3 val n = nums.filter {
4 if (it % 2 == 0) {
5 return it // it was returned from the
main f
6 }
7 }
8 }
// we can use labled return syntax
1 fun main() {
2 val nums = mutableListOf(1,2,3,4,5,6)
3 val n = nums.filter {
4 if (it % 2 == 0) {
5 return@filter it
6 //it was returned from the filter
7 }
8 }
9 }