Skip to content

Instantly share code, notes, and snippets.

@melastmohican
Last active May 23, 2022 04:46
Show Gist options
  • Save melastmohican/a580a3f3833ce59db217af057f9aa0fa to your computer and use it in GitHub Desktop.
Save melastmohican/a580a3f3833ce59db217af057f9aa0fa to your computer and use it in GitHub Desktop.
Learning Kotlin
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"id": "d13f3bc1-69f4-468d-9b21-649b25a78663",
"metadata": {},
"source": [
"### Kotlin snippets"
]
},
{
"cell_type": "markdown",
"id": "ba5ca5fe",
"metadata": {},
"source": [
"#### Equivalent of Java’s main function"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "8c219e50",
"metadata": {},
"outputs": [],
"source": [
"// This syntax is possible\n",
"fun main(vararg argv:String) {\n",
" // Your code\n",
"}\n",
"\n",
"// This one also\n",
"object Main {\n",
" @JvmStatic\n",
" fun main(args: Array<String>) {\n",
" // Your code\n",
" }\n",
"}"
]
},
{
"cell_type": "markdown",
"id": "811cc7d0",
"metadata": {},
"source": [
"#### Scope functions"
]
},
{
"cell_type": "markdown",
"id": "49261eec",
"metadata": {},
"source": [
"##### let\n",
"It can be used to invoke one or more functions on results of call chains."
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "104918f0",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Line_4.jupyter-kts (2:19 - 33) Unresolved reference: getBasicSalary\n",
"Line_4.jupyter-kts (3:1 - 13) Unresolved reference: calculateHRA\n",
"Line_4.jupyter-kts (4:1 - 12) Unresolved reference: calculateDA\n",
"Line_4.jupyter-kts (5:1 - 12) Unresolved reference: calculateTA\n",
"Line_4.jupyter-kts (7:1 - 15) Unresolved reference: getBasicSalary\n",
"Line_4.jupyter-kts (8:5 - 17) Unresolved reference: calculateHRA\n",
"Line_4.jupyter-kts (8:18 - 20) Unresolved reference: it\n",
"Line_4.jupyter-kts (9:5 - 16) Unresolved reference: calculateDA\n",
"Line_4.jupyter-kts (9:17 - 19) Unresolved reference: it\n",
"Line_4.jupyter-kts (10:5 - 16) Unresolved reference: calculateTA\n",
"Line_4.jupyter-kts (10:17 - 19) Unresolved reference: it"
]
}
],
"source": [
"//Without let\n",
"val basicSalary = getBasicSalary()\n",
"calculateHRA(basicSalary)\n",
"calculateDA(basicSalary)\n",
"calculateTA(basicSalary)\n",
"//With let\n",
"getBasicSalary().let {\n",
" calculateHRA(it)\n",
" calculateDA(it)\n",
" calculateTA(it)\n",
"}"
]
},
{
"cell_type": "markdown",
"id": "530518d6",
"metadata": {},
"source": [
"##### apply\n",
"Use it when you accessing multiple properties of an object."
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "f7a97b1e",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"User(name=me, [email protected])\n",
"User(name=me, [email protected])\n"
]
}
],
"source": [
"data class User(var name: String = \"\", var email: String = \"\")\n",
"\n",
"//Without apply\n",
"var user = User()\n",
"user.name = \"me\"\n",
"user.email = \"[email protected]\"\n",
"//With apply\n",
"var user1 = User().apply {\n",
" name = \"me\"\n",
" email = \"[email protected]\"\n",
"}\n",
"println(user)\n",
"println(user1)"
]
},
{
"cell_type": "markdown",
"id": "7e1d8a05",
"metadata": {},
"source": [
"##### with\n",
"It is also used to call multiple methods on the same object.\n"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "6c9e15b5",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"fun calculateHRA(basicSalary: Int) = 1 * basicSalary\n",
"fun calculatePF(basicSalary: Int) = 2 * basicSalary\n",
"\n",
"val basicSalary = 0\n",
"\n",
"//Without\n",
"calculateHRA(basicSalary)\n",
"calculatePF(basicSalary)\n",
"//Using with\n",
"with(basicSalary) {\n",
" calculateHRA(this)\n",
" calculatePF(this)\n",
"}"
]
},
{
"cell_type": "markdown",
"id": "d05a6b7a",
"metadata": {},
"source": [
"### run\n",
"It is also a scope function and useful when you want to do object initialization and some computation of return value."
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "afce184e",
"metadata": {},
"outputs": [],
"source": [
"data class User(var name: String = \"\", var email: String = \"\")\n",
"fun User.formatAddress() = \"Home\"\n",
"\n",
"val user = User().run {\n",
" name = \"Simson\"\n",
" formatAddress()\n",
"}"
]
},
{
"cell_type": "markdown",
"id": "5690e1b9",
"metadata": {},
"source": [
"#### Default parameters\n",
"Default parameters allow us to give default values to a function’s parameter. So when calling this function if you do not pass the second parameter then it takes the default value of 0 and if you pass any value then the function will use that passed value. This will allow us to use method overloading without having to write multiple method signatures for different numbers of arguments."
]
},
{
"cell_type": "code",
"execution_count": 71,
"id": "48745424",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n",
"3\n"
]
}
],
"source": [
"fun add(one: Int, two: Int = 0) = one + two\n",
"\n",
"println(add(1))\n",
"println(add(1,2))"
]
},
{
"cell_type": "markdown",
"id": "b0346c02",
"metadata": {},
"source": [
"#### Extension functions \n",
"Extension functions are functions that are defined for specific data types and calling these functions is the same as member functions with the (.) operator. Extension function is used to extend the functionality of a specific class by creating functions that are only called upon that class object and are user-defined. With the extension functions, we can add more functions to the classes that we don’t have access to like built-in classes (Ex. Int, String, ArrayList, etc..). Kotlin has many inbuilt extension functions like toString(), filter(), map(), toInt() etc.."
]
},
{
"cell_type": "code",
"execution_count": 72,
"id": "2bcafe85",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Square is 25\n",
"convertThisToCamelcase\n"
]
}
],
"source": [
"fun Int.returnSquare(): Int { return this * this }\n",
"val number = 5\n",
"println(\"Square is ${number.returnSquare()}\")\n",
"\n",
"fun String.spaceToCamelCase(): String {\n",
" var l = this.split(\" \").toMutableList()\n",
" for(index in l.indices) {\n",
" if(index > 0) {\n",
" l[index] = l[index].replaceFirstChar { it.uppercase() }\n",
" } else {\n",
" l[index] = l[index].replaceFirstChar { it.lowercase() }\n",
" }\n",
" }\n",
" return l.joinToString(\"\")\n",
"}\n",
"println(\"Convert this to camelcase\".spaceToCamelCase())"
]
},
{
"cell_type": "markdown",
"id": "5cc82fc5",
"metadata": {},
"source": [
"#### String interpolation"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "70fe9d16",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The value of dummyVal is 56 dummyVal * 2 => 112 The name of dummyUser is Foo"
]
}
],
"source": [
"data class User(var name: String = \"\", var email: String = \"\")\n",
"\n",
"val dummyVal = 56\n",
"val dummyUser = User(name=\"Foo\") \n",
"\n",
"// Variable interpolation\n",
"print(\"The value of dummyVal is $dummyVal \")\n",
"\n",
"// Function interpolation\n",
"print(\"dummyVal * 2 => ${dummyVal*2} \")\n",
"\n",
"// Object member interpolation\n",
"print(\"The name of dummyUser is ${dummyUser.name}\")"
]
},
{
"cell_type": "markdown",
"id": "c0d2b557",
"metadata": {},
"source": [
"#### null safe operator (?.)\n",
"is used on nullable type variables to safely use them in code and avoid nullPointerException."
]
},
{
"cell_type": "code",
"execution_count": 35,
"id": "79a311b5",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Unable to instantiate class Line_34"
]
}
],
"source": [
"fun getFiles(): List<String>? = listOf(\"readme.md\",\"help.md\")\n",
"\n",
"val files = getFiles()\n",
"println(files?.size)"
]
},
{
"cell_type": "markdown",
"id": "df3bbc1d",
"metadata": {},
"source": [
"#### Execute block of code if not null"
]
},
{
"cell_type": "code",
"execution_count": 40,
"id": "e424cd51",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Snippet cannot be evaluated due to history mismatch"
]
}
],
"source": [
"data class User(var name: String = \"\", var email: String = \"\")\n",
"\n",
"val alfred = User(name=\"Alfred\")\n",
"\n",
"alfred?.let {\n",
"\tprint(\"My name is ${it.name}\")\n",
"}"
]
},
{
"cell_type": "markdown",
"id": "f9e14cea",
"metadata": {},
"source": [
"#### Call object function if not null"
]
},
{
"cell_type": "code",
"execution_count": 42,
"id": "e2031aa6",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Snippet cannot be evaluated due to history mismatch"
]
}
],
"source": [
"data class User(var name: String = \"\", var email: String = \"\")\n",
"fun User.sayHello() = println(\"Hello ! I'm Alfred\")\n",
"\n",
"val alfred: User? = User(name=\"Alfred\")\n",
"var batman: User? = null\n",
"\n",
"alfred?.sayHello()\n",
"batman?.sayHello()"
]
},
{
"cell_type": "markdown",
"id": "1d2eaae8",
"metadata": {},
"source": [
"#### Get variable's value or other if the variable is null"
]
},
{
"cell_type": "code",
"execution_count": 43,
"id": "ef1aec89",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Snippet cannot be evaluated due to history mismatch"
]
}
],
"source": [
" val x = null\n",
" val y = x ?: 3 "
]
},
{
"cell_type": "markdown",
"id": "45628fed",
"metadata": {},
"source": [
"#### Elvis operator(?:)"
]
},
{
"cell_type": "code",
"execution_count": 46,
"id": "ca9dce7a",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Snippet cannot be evaluated due to history mismatch"
]
}
],
"source": [
"data class User(var name: String? = null, var email: String? = null)\n",
"\n",
"var userName: String? = \"\"\n",
"val user = User()\n",
"//Without \n",
"if(user.name != null) {\n",
" userName = user.name\n",
"} else {\n",
" throw IllegalStateException()\n",
"}\n",
"//With\n",
"val userName1 = user.name?: throw IllegalStateException()"
]
},
{
"cell_type": "markdown",
"id": "90e6205b",
"metadata": {},
"source": [
"### Execute multiple statements if the value is null with run\n"
]
},
{
"cell_type": "code",
"execution_count": 79,
"id": "e1f1b151",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Line_78.jupyter-kts (3:3 - 4) Expecting an element"
]
}
],
"source": [
"user.name?.let{\n",
" // Excecute if not null\n",
"} : run {\n",
" //Execute if null\n",
"}"
]
},
{
"cell_type": "markdown",
"id": "e42ebcfa",
"metadata": {},
"source": [
"#### Single-expression functions\n",
"If a function just returns a value then you can write it in single-expression."
]
},
{
"cell_type": "code",
"execution_count": 80,
"id": "921e75d5",
"metadata": {},
"outputs": [],
"source": [
"fun isOdd(number:Int) = if(number%2 ==0) false else true"
]
},
{
"cell_type": "markdown",
"id": "9b7453f0",
"metadata": {},
"source": [
"#### Range operator(..)"
]
},
{
"cell_type": "code",
"execution_count": 81,
"id": "c55a20f1",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Line_80.jupyter-kts (4:39 - 39) Expecting an expression"
]
}
],
"source": [
"for( i in 1..10) // 1 to 10\n",
"for( i in 1 until 10) // 1 to 9 (Does not include 10)\n",
"for( i in 1..10 step 2) // 1,3,5,7,9\n",
"for( i in 10 downTo 1) // 10,9,8....,1"
]
},
{
"cell_type": "markdown",
"id": "d343a356",
"metadata": {},
"source": [
"#### Check Instance with is operator"
]
},
{
"cell_type": "code",
"execution_count": 82,
"id": "b46dfd76",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Line_81.jupyter-kts (3:29 - 29) Expecting an expression"
]
}
],
"source": [
"if(10 is Int) // true\n",
"if(10 is Boolean) // false\n",
"if(\"string\" !is Int) // true"
]
},
{
"cell_type": "markdown",
"id": "d64b5874",
"metadata": {},
"source": [
"#### Lambda functions\n",
"Lambda functions are anonymous functions that we can treat as values. We can pass lambda functions as arguments and store them as variables."
]
},
{
"cell_type": "code",
"execution_count": 83,
"id": "3a1b0b6d",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Line_82.jupyter-kts (1:3 - 15) Parameter 'argumentName' is never used, could be renamed to _\n",
"Line_82.jupyter-kts (1:17 - 29) Unresolved reference: argumentType"
]
}
],
"source": [
"{ argumentName: argumentType -> \n",
" // lambda body\n",
"}"
]
},
{
"cell_type": "markdown",
"id": "f9371d98",
"metadata": {},
"source": [
"Argument name and type are optional, we can omit that. Lambda body is required. The type of the last line of lambda body is the return type of lambda."
]
},
{
"cell_type": "code",
"execution_count": 84,
"id": "3bd8021d",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"25\n"
]
}
],
"source": [
"val double: (Int)-> Int = {number:Int -> number * number}\n",
"println(double(5))"
]
},
{
"cell_type": "markdown",
"id": "b82b292b",
"metadata": {},
"source": [
"#### Sort hashmap by value"
]
},
{
"cell_type": "code",
"execution_count": 85,
"id": "fc2339a5",
"metadata": {},
"outputs": [],
"source": [
"val weights = hashMapOf(\"Foo\" to 68, \"Bar\" to 30, \"Baz\" to 10)\n",
"\n",
"// Ascending order\n",
"val sortedWeightsAsc = weights.toList().sortedBy { (key,value) -> value } \n",
"\n",
"// Descending order\n",
"val sortedWeightsDesc = weights.toList().sortedByDescending { (key,value) -> value }"
]
},
{
"cell_type": "markdown",
"id": "90b2ef64",
"metadata": {},
"source": [
"#### Equivalent of switch case"
]
},
{
"cell_type": "code",
"execution_count": 86,
"id": "372a5ad9",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Wut ?"
]
}
],
"source": [
"val choice = \"ok\"\n",
"\n",
"when (choice) {\n",
" \"red\" -> {\n",
" //Block of code between curly braces\n",
" }\n",
" \"blue\" -> print(\"Blue !!!\") // Single instruction\n",
" else -> print(\"Wut ?\") // Default \n",
"}"
]
},
{
"cell_type": "markdown",
"id": "50cf40f1",
"metadata": {},
"source": [
"#### Human-readable object members modification"
]
},
{
"cell_type": "code",
"execution_count": 48,
"id": "f9dce81e",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Snippet cannot be evaluated due to history mismatch"
]
}
],
"source": [
"data class User(var name: String? = null, var age: Int = 0, var dateOfBirth: String? = null)\n",
"\n",
"val toto = User(name=\"Toto\", age=36, dateOfBirth=\"05-23-1998\")\n",
"\n",
"toto.apply {\n",
"\tname=\"Foo\"\n",
"\tage=41\n",
"\tdateOfBirth=\"01-01-2018\"\n",
"}\n"
]
},
{
"cell_type": "markdown",
"id": "8a8ae33d",
"metadata": {},
"source": [
"#### Check if element is in list"
]
},
{
"cell_type": "code",
"execution_count": 49,
"id": "29d5be49",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Snippet cannot be evaluated due to history mismatch"
]
}
],
"source": [
"val numbers = listOf(1,30,45,73,2,19)\n",
"\n",
"if( 1 in numbers ) {\n",
"\t// Code\n",
"}"
]
},
{
"cell_type": "markdown",
"id": "2394c2b5",
"metadata": {},
"source": [
"#### Remove elements of a list based on certain conditions"
]
},
{
"cell_type": "code",
"execution_count": 89,
"id": "41d7896e",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[black tiger, white tiger, red tiger, golden tiger]"
]
}
],
"source": [
"val animals = listOf(\"black tiger\", \"white tiger\", \"red tiger\", \"golden tiger\", \"fish\", \"lion\", \"cat\", \"dog\")\n",
"var tigers: List<String> = emptyList()\n",
"\n",
"// Contains style\n",
"tigers = animals.filter { it.contains(\"tiger\") }\n",
"\n",
"// Kotlin style\n",
"tigers = animals.filter { \"tiger\" in it }\n",
"\n",
"// Kotlin parameterized style\n",
"tigers = animals.filter { animal -> \"tiger\" in animal }\n",
"\n",
"print(tigers)"
]
},
{
"cell_type": "markdown",
"id": "63f8f5d6",
"metadata": {},
"source": [
"#### Apply function to all elements of a list"
]
},
{
"cell_type": "code",
"execution_count": 90,
"id": "0c00ecb5",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[2, 4, 6, 8, 10]"
]
}
],
"source": [
"val numbers = listOf(1,2,3,4,5)\n",
"val doubles = numbers.map { it*2 }\n",
"\n",
"print(doubles)"
]
},
{
"cell_type": "markdown",
"id": "20c7db50",
"metadata": {},
"source": [
"#### Check that at least one element of a list verifies conditions"
]
},
{
"cell_type": "code",
"execution_count": 91,
"id": "6b8d5b1c",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"At least one element > 4"
]
}
],
"source": [
"val numbers = listOf(1,2,3,4,5)\n",
"\n",
"if(numbers.any { it > 4 } )\n",
"\tprint(\"At least one element > 4\")"
]
},
{
"cell_type": "markdown",
"id": "40892cbd",
"metadata": {},
"source": [
"#### Retrieve the first element of a list matching conditions"
]
},
{
"cell_type": "code",
"execution_count": 92,
"id": "298b11d9",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"black tiger"
]
}
],
"source": [
"val animals = listOf(\"black tiger\", \"white tiger\", \"red tiger\", \"golden tiger\", \"fish\", \"lion\", \"cat\", \"dog\")\n",
"val firstTiger = animals.first { it.contains(\"tiger\") }\n",
"\n",
"// You can replace first with firstOrNull, self-explanatory\n",
"print(firstTiger)"
]
},
{
"cell_type": "markdown",
"id": "c65768a6",
"metadata": {},
"source": [
"#### Variable conditional assignation"
]
},
{
"cell_type": "code",
"execution_count": 93,
"id": "5b326a35",
"metadata": {},
"outputs": [],
"source": [
"val a = 5\n",
"\n",
"val x = when(a) {\n",
"\t1 -> \"a is equal to 1\"\n",
"\t3 -> \"wut ?\"\n",
"\telse -> \"a is a big int\"\n",
"}\n",
"// x = \"a is a big int\", because of a = 5 "
]
},
{
"cell_type": "markdown",
"id": "594ef65e",
"metadata": {},
"source": [
"#### Human-readable for loops"
]
},
{
"cell_type": "code",
"execution_count": 94,
"id": "d386094e",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"12345123454321135foobarbazThere are 3 milk(s) in this cart\n",
"There are 3 apple(s) in this cart\n",
"There are 8 steak(s) in this cart\n"
]
}
],
"source": [
"for (i in 1..5)\n",
"\tprint(i) // Produces 12345\n",
"\n",
"for (i in 1 until 5)\n",
"\tprint(i) // Produces 1234\n",
"\n",
"for (i in 5 downTo 1)\n",
"\tprint(i) // Produces 54321\n",
"\n",
"for (i in 1..5 step 2)\n",
"\tprint(i) // Produces 135\n",
"\n",
"for (i in listOf(\"foo\",\"bar\",\"baz\"))\n",
"\tprint(i) // Produces foobarbaz\n",
"\n",
"for ( (ingredient,quantity) in hashMapOf(\"apple\" to 3, \"steak\" to 8, \"milk\" to 3) )\n",
" print(\"There are $quantity $ingredient(s) in this cart\\n\")\n",
"\n",
"/* Last output : \n",
"\t\tThere are 8 steak(s) in this cart\n",
"\t\tThere are 3 milk(s) in this cart\n",
"\t\tThere are 3 apple(s) in this cart\n",
"*/"
]
},
{
"cell_type": "markdown",
"id": "13ee67e3",
"metadata": {},
"source": [
"#### Extension functions\n",
"Extension functions are functions that are defined for specific data types and calling these functions is the same as member functions with the (.) operator. Extension function is used to extend the functionality of a specific class by creating functions that are only called upon that class object and are user-defined. With the extension functions, we can add more functions to the classes that we don’t have access to like built-in classes (Ex. Int, String, ArrayList, etc..). Kotlin has many inbuilt extension functions like toString(), filter(), map(), toInt() etc.."
]
},
{
"cell_type": "code",
"execution_count": 95,
"id": "1f1350d8",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2 power 10 is 1024\n",
"Square of 5 is 25\n"
]
},
{
"data": {
"text/plain": [
"Convert, this, to, camelcase"
]
},
"execution_count": 95,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"fun Int.power(b: Int): Int { \n",
" var tmpInt = this \n",
" if (b == 0) return 1\n",
" for (i in 1 until b) tmpInt *= this\n",
" return tmpInt\n",
"}\n",
"\n",
"println(\"2 power 10 is ${2.power(10)}\")\n",
"\n",
"fun Int.square(): Int { return this * this }\n",
"val number = 5\n",
"println(\"Square of ${number} is ${number.square()}\")\n",
"\n",
"fun String.spaceToCamelCase(): String {\n",
" val l = this.split(\" \")\n",
" l.forEach { it[0].uppercase() }\n",
" return l.joinToString()\n",
"}\n",
"\"Convert this to camelcase\".spaceToCamelCase()"
]
},
{
"cell_type": "markdown",
"id": "6523d763",
"metadata": {},
"source": [
"#### Use infix notation to have a more readable and beautiful code"
]
},
{
"cell_type": "code",
"execution_count": 96,
"id": "112ad1c3",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1024"
]
}
],
"source": [
"infix fun Int.power(b: Int): Int { \n",
" var tmpInt = this\n",
" \n",
" if (b == 0) \n",
" return 1\n",
"\n",
" for (i in 1 until b)\n",
" tmpInt *= this\n",
"\n",
" return tmpInt\n",
"}\n",
"\n",
"print(2 power 10) // Produces 1024"
]
},
{
"cell_type": "markdown",
"id": "62357f5c",
"metadata": {},
"source": [
"#### Higher-order functions aka functions passed as parameters"
]
},
{
"cell_type": "code",
"execution_count": 97,
"id": "938af798",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<u>Awesome text !</u><strong>Awesome text !</strong><i>Awesome text !</i>"
]
}
],
"source": [
"abstract class TextFormattingStrategy {\n",
" abstract fun format(text: String): String\n",
"}\n",
"\n",
"\n",
"class UnderlineStrategy : TextFormattingStrategy() {\n",
" override fun format(text: String): String {\n",
" return \"<u>$text</u>\"\n",
" }\n",
"}\n",
"\n",
"class BoldStrategy : TextFormattingStrategy() {\n",
" override fun format(text: String): String {\n",
" return \"<strong>$text</strong>\"\n",
" }\n",
"}\n",
"\n",
"class ItalicStrategy : TextFormattingStrategy() {\n",
"\t// You can use this syntax too\n",
" override fun format(text: String): String = \"<i>$text</i>\" \n",
"}\n",
"\n",
"fun format(text: String, strategy: TextFormattingStrategy): String {\n",
" return strategy.format(text)\n",
"}\n",
"\n",
"val text = \"Awesome text !\"\n",
"\n",
"print(format(text, UnderlineStrategy())) // Produces <u>Awesome text !</u>\n",
"print(format(text, BoldStrategy())) // Produces <strong>Awesome text !</strong>\n",
"print(format(text, ItalicStrategy())) // Produces <i>Awesome text !</i>"
]
},
{
"cell_type": "markdown",
"id": "47a1c1b6",
"metadata": {},
"source": [
"#### Measure time elapsed during function execution"
]
},
{
"cell_type": "code",
"execution_count": 98,
"id": "7dfe4405",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Line_97.jupyter-kts (8:7 - 24) Unresolved reference: measureTimeMillis"
]
}
],
"source": [
"fun longTreatment() {\n",
"\t for (i in 0..10000000000) {\n",
"\t // Nothing, just keep running\n",
"\t }\n",
"}\n",
"\n",
"// This function is part of the Kotlin Standard Library\n",
"print(measureTimeMillis { longTreatment() }) // Produces 4323 ms"
]
},
{
"cell_type": "markdown",
"id": "97cee30d",
"metadata": {},
"source": [
"#### Declare a Matrix / 2D Array"
]
},
{
"cell_type": "code",
"execution_count": 99,
"id": "752122e2",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0 0 0 0 0 |\n",
"0 0 0 0 0 |\n",
"0 0 0 0 0 |\n",
"0 0 0 0 0 |\n",
"0 0 0 0 0 |\n"
]
}
],
"source": [
"inline fun <reified T> matrix(height: Int, width: Int, initialize: () -> T) = Array(height) { Array(width) { initialize() } }\n",
"\n",
"val board = matrix(5, 5) { 0 }\n",
"\n",
"board.forEach { row ->\n",
" row.forEach { column ->\n",
" print(\"$column \")\n",
" }\n",
" print(\"|\\n\")\n",
"}\n",
"\n",
"/* Output : \n",
"\t\t0 0 0 0 0 |\n",
"\t\t0 0 0 0 0 |\n",
"\t\t0 0 0 0 0 |\n",
"\t\t0 0 0 0 0 |\n",
"\t\t0 0 0 0 0 | \n",
"*/ "
]
},
{
"cell_type": "markdown",
"id": "4aaf7f83",
"metadata": {},
"source": [
"#### Declare data class"
]
},
{
"cell_type": "code",
"execution_count": 100,
"id": "db5568a5",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello, I'm Toto\n",
"I'm his friend ! Foo - 19yo !"
]
}
],
"source": [
"data class User(val name: String, val age: Int)\n",
"\n",
"// Notice that in Kotlin the 'new' keyword doesn't exist\n",
"val toto = User(\"Toto\", 18)\n",
"\n",
"// You can initialize objects with named arguments\n",
"val foo = User(name = \"Foo\", age = 19)\n",
"\n",
"// You can access members of those objects directly\n",
"print(\"Hello, I'm ${toto.name}\\n\")\n",
"print(\"I'm his friend ! ${foo.name} - ${foo.age}yo !\")"
]
},
{
"cell_type": "markdown",
"id": "4f6a16ca",
"metadata": {},
"source": [
"provides a `User` class with the following functionality:\n",
"\n",
"- getters (and setters in case of *var*{: .keyword }s) for all\n",
" properties\n",
"- `equals()`\n",
"- `hashCode()`\n",
"- `toString()`\n",
"- `copy()`\n",
"- `component1()`, `component2()`, …, for all properties (see [Data\n",
" classes](http://www.tellmehow.co/recyclerview%e2%80%8a-%e2%80%8adelegate-adapters-data-classes-kotlin/))"
]
},
{
"cell_type": "markdown",
"id": "d832b3e6",
"metadata": {},
"source": [
"#### Declare a singleton"
]
},
{
"cell_type": "code",
"execution_count": 101,
"id": "4249c4e3",
"metadata": {},
"outputs": [],
"source": [
"data class User(val name: String, val age: Int)\n",
"\n",
"object UserFactory { // Practice design patterns while learning Kotlin <3\n",
"\tval userList: ArrayList<User> = ArrayList()\n",
"\n",
"\tfun createUser(name: String, age: Int): User {\n",
"\t val createdUser = User(name, age)\n",
"\t userList.add(createdUser)\n",
"\t return createdUser\n",
"\t}\n",
"}\n",
"\n",
"// Notice that UserFactory is called without having been instantiated before with something like 'val uf = UserFactory()'\n",
"val foo = UserFactory.createUser(\"Foo\",18)"
]
},
{
"cell_type": "markdown",
"id": "957fe0eb",
"metadata": {},
"source": [
"#### Operator overloading\n",
"See full reference at : [Kotlin overloading operators reference](https://kotlinlang.org/docs/operator-overloading.html) :thumbsup:"
]
},
{
"cell_type": "code",
"execution_count": 102,
"id": "cb32162f",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"120"
]
}
],
"source": [
"operator fun Int.not(): Int { // operator overloaded : !\n",
" var tmpInt = 1\n",
" for (i in 1..this) // Basic factorial implementation\n",
" tmpInt *= i\n",
" return tmpInt\n",
"}\n",
"\n",
"print(!5) // Produces 120"
]
},
{
"cell_type": "markdown",
"id": "6d034f85",
"metadata": {},
"source": [
"#### Cool syntactic sugars"
]
},
{
"cell_type": "code",
"execution_count": 103,
"id": "e0693b10",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Line_102.jupyter-kts (13:49 - 49) Expecting ')'"
]
}
],
"source": [
"/*************************************************************/\n",
"val cart = hashMapOf(\"apple\" to 3, \"steak\" to 8, \"milk\" to 3)\n",
"\n",
"// You can use the '_' wildcard for parameters you don't use\n",
"val vegetables = cart.filter { (key,_) -> \"steak\" !in key }\n",
"\n",
"/*************************************************************/\n",
"fun logExecution(a: Int, b: String, f: () -> Unit) {\n",
"\t// Code\n",
"}\n",
"\n",
"// If a function is passed as the last parameter of a higher-order function, you can write it like this\n",
"logExecution(3,\"dummy string\") { print(\"Hello !\" } \n",
"\n",
"// Instead of (inside parenthesis)\n",
"logExecution(3, \"dummy string\", { print(\"Hello !\") } )\n",
"\n",
"/*************************************************************/\n",
"Incoming <3"
]
},
{
"cell_type": "markdown",
"id": "e513cd2b",
"metadata": {},
"source": [
"#### Kotlin built-in functions"
]
},
{
"cell_type": "markdown",
"id": "b635ab01",
"metadata": {},
"source": [
"##### filter\n",
"Filters the list, set, or map with the given predicate and returns a list, set, or map with elements that match the predicate."
]
},
{
"cell_type": "code",
"execution_count": 104,
"id": "401ed810",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[2, 4]\n",
"[2, 3, 4]\n",
"[4, 5]\n"
]
}
],
"source": [
"val numbers = listOf(1,2,3,4,5)\n",
"println(numbers.filter {element-> element%2 == 0 }) \n",
"println(numbers.filterIndexed{index,element->(index != 0) && (element< 5)})\n",
"println(numbers.filterNot {element-> element <= 3 })"
]
},
{
"cell_type": "markdown",
"id": "3b8111b1",
"metadata": {},
"source": [
"##### map\n",
"Applies given predicate or transformation function to each element of the collection and returns a new collection."
]
},
{
"cell_type": "code",
"execution_count": 106,
"id": "68ea22b8",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, 2, 3, 4, 5]\n",
"[3, 6, 9, 12, 15]\n",
"[0, 2, 6, 12, 20]\n",
"[3, 9, 12, 15]\n",
"[2, 6, 12, 20]\n",
"{key1=1, key2=2, key3=3, key11=11}\n",
"{KEY1=1, KEY2=2, KEY3=3, KEY11=11}\n",
"{key1=5, key2=6, key3=7, key11=16}\n"
]
}
],
"source": [
"val numbers = listOf(1,2,3,4,5)\n",
"println(numbers)\n",
"val numbers1 = numbers.map { it * 3 }\n",
"println(numbers1);\n",
"val numbers2 = numbers.mapIndexed { index,value -> value * index }\n",
"println(numbers2)\n",
"//following functions are used to get non-null values\n",
"val numbers3 = numbers.mapNotNull {value-> if ( value == 2) null else value * 3 }\n",
"println(numbers3)\n",
"val numbers4 = numbers.mapIndexedNotNull { \n",
" index, value -> if (index == 0) null else value * index \n",
"}\n",
"println(numbers4)\n",
"\n",
"val numbersMap = mapOf(\"key1\" to 1, \"key2\" to 2, \"key3\" to 3, \"key11\" to 11)\n",
"println(numbersMap)\n",
"println(numbersMap.mapKeys { it.key.uppercase() })\n",
"println(numbersMap.mapValues { it.value + it.key.length })"
]
},
{
"cell_type": "markdown",
"id": "090ed8b9",
"metadata": {},
"source": [
"##### zip \n",
"It creates a list of pairs with elements of the same index from the given two lists."
]
},
{
"cell_type": "code",
"execution_count": 107,
"id": "dda36510",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[(red, fox), (brown, bear), (grey, wolf)]\n"
]
}
],
"source": [
"val colors = listOf(\"red\", \"brown\", \"grey\")\n",
"val animals = listOf(\"fox\", \"bear\", \"wolf\")\n",
"println(colors.zip(animals)) "
]
},
{
"cell_type": "markdown",
"id": "62c65242",
"metadata": {},
"source": [
"##### Create two lists from the list of pairs by applying unzip."
]
},
{
"cell_type": "code",
"execution_count": 108,
"id": "13d29395",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"([one, two, three, four], [1, 2, 3, 4])\n"
]
}
],
"source": [
"val numberPairs = listOf(\"one\" to 1, \"two\" to 2, \"three\" to 3, \"four\" to 4)\n",
"println(numberPairs.unzip())"
]
},
{
"cell_type": "markdown",
"id": "f3dc5efd",
"metadata": {},
"source": [
"##### joinToString() \n",
"This will create a string with all elements appended.\n",
"##### joinTo() \n",
"This will create a string with all elements appended and append that to the given string in the argument."
]
},
{
"cell_type": "code",
"execution_count": 109,
"id": "22c6cb35",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"one, two, three, four\n",
"The list of numbers: one, two, three, four\n"
]
}
],
"source": [
"val numbers = listOf(\"one\", \"two\", \"three\", \"four\")\n",
"println(numbers.joinToString())\n",
"val listString = StringBuffer(\"The list of numbers: \")\n",
"println(numbers.joinTo(listString))"
]
},
{
"cell_type": "markdown",
"id": "5c7d1c61",
"metadata": {},
"source": [
"##### flatten()\n",
"It creates one list from the list of lists."
]
},
{
"cell_type": "code",
"execution_count": 115,
"id": "52b55dd1",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, 2, 3, 4, 5, 6, 7]\n"
]
}
],
"source": [
"val listOfList = listOf(listOf(1,2),listOf(3,4,5),listOf(6,7))\n",
"\tprintln(listOfList.flatten())"
]
},
{
"cell_type": "markdown",
"id": "c32b217b",
"metadata": {},
"source": [
"\n",
"##### any \n",
"It takes lambda and checks whether the given predicate in lambda matches any of the elements from the list. If yes then it returns true otherwise false.\n",
"##### all \n",
"If the given predicate matches all the elements of a collection then returns true otherwise false.\n",
"##### none\n",
"If the given predicate does not match any of the elements from the collection then it returns true otherwise false."
]
},
{
"cell_type": "code",
"execution_count": 117,
"id": "fedf26e6",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"true\n",
"true\n",
"false\n"
]
}
],
"source": [
"val numbers = listOf(\"one\", \"two\", \"three\", \"four\")\n",
"println(numbers.any { it.endsWith(\"e\") })\n",
"println(numbers.none { it.endsWith(\"a\") })\n",
"println(numbers.all { it.endsWith(\"e\") })"
]
},
{
"cell_type": "markdown",
"id": "a5b8be0e",
"metadata": {},
"source": [
"##### partition\n",
"It will return pair of lists one with elements that match the condition and one with elements that do not match the condition.\n",
"##### slice\n",
"It will create a list with the given index.\n",
"##### chunked\n",
"It will also create a list of lists but with the given size."
]
},
{
"cell_type": "code",
"execution_count": 119,
"id": "1c4fb673",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"([three, four], [one, two])\n",
"[two, three, four]\n",
"[[one, two], [three, four]]\n"
]
}
],
"source": [
"val numbers = listOf(\"one\", \"two\", \"three\", \"four\")\n",
"println(numbers.partition { it.length > 3 } )\n",
"println(numbers.slice(1..3))\n",
"println(numbers.chunked(2))"
]
},
{
"cell_type": "markdown",
"id": "2f2493b8",
"metadata": {},
"source": [
"##### take\n",
"It will get the specified number of elements starting from the first.\n",
"##### takeLast\n",
"It will get the specified number of elements starting from the last.\n",
"##### drop\n",
"It will take all the elements except a given number of first elements.\n",
"##### dropLast\n",
"It will take all the elements except a given number of last elements."
]
},
{
"cell_type": "code",
"execution_count": 120,
"id": "1bf130eb",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[one, two, three]\n",
"[four, five, six]\n",
"[two, three, four, five, six]\n",
"[one]\n"
]
}
],
"source": [
"val numbers = listOf(\"one\", \"two\", \"three\", \"four\", \"five\", \"six\")\n",
"println(numbers.take(3))\n",
"println(numbers.takeLast(3))\n",
"println(numbers.drop(1))\n",
"println(numbers.dropLast(5))"
]
},
{
"cell_type": "markdown",
"id": "d0eb4882",
"metadata": {},
"source": [
"##### groupBy\n",
"It takes a lambda function and returns a map. In a result map, keys will be the result of lambda functions and values will be the corresponding list element on which the lambda function is applied. It is used to group list elements with specific conditions."
]
},
{
"cell_type": "code",
"execution_count": 121,
"id": "0c7afab8",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{O=[one], T=[two, three], F=[four, five]}\n"
]
}
],
"source": [
"val numbers = listOf(\"one\", \"two\", \"three\", \"four\", \"five\")\n",
"println(numbers.groupBy { it.first().uppercase() })"
]
},
{
"cell_type": "markdown",
"id": "fd20a42d",
"metadata": {},
"source": [
"##### average\n",
"Returns the average of the elements of the list.\n",
"##### sum\n",
"Returns the sum of all the elements of the list.\n",
"##### count\n",
"Returns the count of the elements in the list.\n",
"##### minOrNull\n",
"Returns the smallest value from the list or return null when the list is empty.\n",
"##### maxOrNull\n",
"Returns the largest value from the list or return null when the list is empty."
]
},
{
"cell_type": "code",
"execution_count": 122,
"id": "416834b4",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Count: 4\n",
"Max: 42\n",
"Min: 4\n",
"Average: 15.5\n",
"Sum: 62\n"
]
}
],
"source": [
"val numbers = listOf(6, 42, 10, 4)\n",
"println(\"Count: ${numbers.count()}\")\n",
"println(\"Max: ${numbers.maxOrNull()}\")\n",
"println(\"Min: ${numbers.minOrNull()}\")\n",
"println(\"Average: ${numbers.average()}\")\n",
"println(\"Sum: ${numbers.sum()}\") "
]
},
{
"cell_type": "markdown",
"id": "6db35f95",
"metadata": {},
"source": [
"### ‘try/catch’ expression"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4723753e",
"metadata": {},
"outputs": [],
"source": [
"fun test() {\n",
" val result = try {\n",
" count()\n",
" } catch (e: ArithmeticException) {\n",
" throw IllegalStateException(e)\n",
" }\n",
"\n",
" // Working with result\n",
"}"
]
},
{
"cell_type": "markdown",
"id": "e2e633d7",
"metadata": {},
"source": [
"### Builder-style usage of methods that return `Unit`"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9b408851",
"metadata": {},
"outputs": [],
"source": [
"fun arrayOfMinusOnes(size: Int): IntArray {\n",
" return IntArray(size).apply { fill(-1) }\n",
"}"
]
},
{
"cell_type": "markdown",
"id": "b65d88c5",
"metadata": {},
"source": [
"### Java 7’s try with resources"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "485a8837",
"metadata": {},
"outputs": [],
"source": [
"val stream = Files.newInputStream(Paths.get(\"/some/file.txt\"))\n",
"stream.buffered().reader().use { reader ->\n",
" println(reader.readText())\n",
"}"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Kotlin",
"language": "kotlin",
"name": "kotlin"
},
"language_info": {
"codemirror_mode": "text/x-kotlin",
"file_extension": ".kt",
"mimetype": "text/x-kotlin",
"name": "kotlin",
"nbconvert_exporter": "",
"pygments_lexer": "kotlin",
"version": "1.7.0-dev-3303"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment