Kotlin Cheatsheet

Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

Kotlin Cheatsheet

"Hello, world" example

1 fun main() {
2 println("Hello World!")
3 }

Variables
val -> read-only or assigned-once
var -> mutable

// can omit types for the variable

1 val name = "Sriram"

// but you can modify an object stored using val

1 val languages = mutableListOf("Java")


2 languages.add("Kotlin")

// you can't modify an read-only object stored using val


1 val languages = listOf("Java")
2 languages.add("Kotlin") // error

Functions

1 fun max(a: Int, b: Int): Int {


2 return if ( a > b ) a else b
3 }

// if function returns one expression


// you can use function with expression body

1 fun max(a: Int, b: Int): Int = if ( a > b ) a else


b

Named & default arguments

1 fun aboutYou(name: String, age: int) {


2 println("Hi $name")
3 println("you are $age years old")
4 }
// named arguments

1 aboutYou(name = "Sriram", age = "18")

// default values to the parameter

1 fun aboutYou(name: String = "sham", age: int = 18)


{
2 println("Hi $name")
3 println("you are $age years old")
4 }

// 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 you need to provide value to the second argument


// then you should use named argument
1 aboutYou(age = 20)
Conditionals: if & when

// 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 }

// using when as expression


1 var degrees = 4
2 val colour = when {
3 degrees < 5 -> "cold"
4 degrees < 23 -> "mild"
5 else -> "hot"
6 }
Loops

// for loop
1 val list = listOf("a", "b", "c", "d", "e")
2 for (i in list) {
3 println(s)
4 }

// Iterating over map


1 val map = mapOf(1 to "one",
2 2 to "two",
3 3 to "three")
4 for ((key, value) in map) {
5 println("$key = $value")
6 }

// Iterating over range

1 for (i in 1..9) {
2 println(i)
3 }

// Iterating while excluding upper bound


1 for (i in 1 until 9) {
2 println(i)
3 }
// Iterating with step

1 for (i in 1 until 9 step 2) {


2 println(i)
3 }

// Iterating over String

1 for (i in "abcdefg") {
2 println(i)
3 }

'in' checks & ranges


// in can be used to check for belonging which returns a boolean value

1 println("a" in "abcdef")

// not in a range
1 println(6 !in listOf(1,2,3,4,5))
// in as when-condition

1 fun evenOrOdd(n: Int): String = when (n) {


2 in listOf(1,3,5,7,9) -> "odd"
3 in listOf(2,4,6,8,10) -> "even"
4 else -> "I don't know, it is greater than 10"
5 }

// different ranges

1 val intRange: IntRange = 1..9


2 val charRange: CharRange = 'a'..'z'
3 val stringRange: ClosedRange<String> = "ab".."az"

Exceptions

// try is an expression

1 val number = try {


2 Integer.parseInt("string")
3 } catch (e: NumberFormatException) {
4 null
5 }
Extension Functions

// extension function extends the class


// it is defined outside of the class
// but can be called as a regular member of the class

1 fun String.lastChar() = this.get(this.length - 1)


2 println("abcd".lastChar())

// "this" can be omitted

1 fun String.lastChar() = get(length -1)


2 println("abcd".lastChar())

// you cannot call a private member of the class inside an


extension function

// infix function, either call it in a regular way,


// or call it by omitting dot and parentheses
1 infix fun Int.until(to: Int): IntRange
2 1.until(10)
3 1 until 10
// to as extension function gives a pair

1 infix fun <A, B> A.to(that: B) = Pair(this, that)


2 "hot" to 10

Calling Extensions

// extension functions are static Java functions under the hood


// No override for extension functions in Kotlin

// "parent" will be printed here

1 open class Parent


2 class Child: Parent()
3
4 fun Parent.foo() = "parent"
5 fun Child.foo() = "child"
6
7 val parent: Parent = Child()
8
9 println(parent.foo())
// extensions don't hide members

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

// extensions can overload members

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

1 var s1:String = "always not null"


2 s1 = null // compile time error
3
4 var s2:String? = "can be null or non-null"
5 s2 = null // no error
6
7
8 s1.length // fine because it always will be non-
null
9 s2.length // compile error
10
11
12// Safeaccess expression to call null object
13// if its not null it calls the member or
14// the result is null
15s2?.length
16
17// you can use elvis operator to handle null
18 var n1: Int = s2?.length ?: 0
19
20
21 // making NPE explicit
22 // not null assertion
23 // !! throws NPE if s2 is null
Safe casts
// you can cast to a type without error

1 val s = 2 as String // error


2
3 val s = (2 as? String)?.uppercase()// returns null
4 // (2 as? String) returns null
5 // by safeaccess expression the error can be
avoided

Lambdas

// lambda syntax

1 {x: Int, y: Int -> x + y}

// finding even numbers in the list

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

// it can move out of the parentheses if lambda is the last argument


// empty parentheses can be omitted
1 val m = n.filter {i -> i % 2 ==0 }
// it can be used if the argument of the lambda is only one
1 val m = n.filter { it % 2 ==0 }

// Multi-line lambda

1 val m = n.filter {
2 println("processing $it")
3 it % 2 ==0 // last expression is the result
4 }

Common Operations on collections


// filter
// it filters the list by the passed condition in the lambda
1 listOf(1,2,3,4).filter { it % 2 == 0 } // [2, 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}

// working with a nullable function type


// we can use safe access expression and call invoke function

1 val f: (() -> Int)? = null


2 f?.invoke()

return from Lambda

// 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 }

You might also like