From 85b193167323f227570117799761c99971f5b088 Mon Sep 17 00:00:00 2001 From: Alexander Nozik Date: Sun, 8 Dec 2024 12:38:44 +0300 Subject: [PATCH] Update notebooks --- notebooks/Idioms.ipynb | 352 ++++++++++++++++++++--------------- notebooks/Multitasking.ipynb | 180 +++++++----------- 2 files changed, 269 insertions(+), 263 deletions(-) diff --git a/notebooks/Idioms.ipynb b/notebooks/Idioms.ipynb index c1ac804..9e9d9a3 100644 --- a/notebooks/Idioms.ipynb +++ b/notebooks/Idioms.ipynb @@ -138,7 +138,7 @@ }, { "cell_type": "code", - "source": "println(\"This is a string with \\$\")", + "source": "println(\"This is a string with \\$a\")", "metadata": { "datalore": { "node_id": "hm9iYlWj1B2S0469GtxDrf", @@ -157,13 +157,16 @@ { "cell_type": "code", "source": [ - "println(\"\"\"\n", + "println(\n", + " \"\"\"\n", + " \\\\\\\n", " This is a \n", " multi\n", " line\n", " raw\n", " string\n", - "\"\"\".trimIndent())" + "\"\"\".trimIndent()\n", + ")" ], "metadata": { "datalore": { @@ -182,9 +185,7 @@ }, { "cell_type": "code", - "source": [ - "println(\"\"\"This is a raw string number ${number+1} with \\ and ${'$'} \"\"\")" - ], + "source": "println(\"\"\"This is a raw string number ${number + 1} with \\ and ${'$'} \"\"\")", "metadata": { "datalore": { "node_id": "KDL3D9lOVn6vX3iTAY50gb", @@ -232,7 +233,7 @@ "source": [ "/* Not recommended */\n", "var counter = 0\n", - "for(i in 0..20){\n", + "for (i in 0..20) {\n", " counter += i\n", "}\n", "counter" @@ -277,7 +278,7 @@ { "cell_type": "code", "source": [ - "val intArray: IntArray = IntArray(21){ it -> it + 1 }\n", + "val intArray: IntArray = IntArray(21) { it -> it + 1 }\n", "intArray.sum()" ], "metadata": { @@ -295,6 +296,20 @@ "outputs": [], "execution_count": null }, + { + "metadata": {}, + "cell_type": "code", + "source": [ + "var _a = 2\n", + "val a: Int get() = _a\n", + "\n", + "println(a)\n", + "_a = 3\n", + "println(a)" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "source": [ @@ -324,7 +339,7 @@ "/**\n", " * Functions could be defined everywhere in kotlin code. This is a so-called top-level function.\n", " */\n", - "fun doSomething(){\n", + "fun doSomething() {\n", " println(\"I did it\")\n", "}\n", "\n", @@ -348,15 +363,15 @@ { "cell_type": "code", "source": [ - "interface AnInterface{\n", + "interface AnInterface {\n", " fun doSomethingInAnObject()\n", "}\n", "\n", - "object AnObject : AnInterface{\n", + "object AnObject : AnInterface {\n", " /**\n", " * This is a member-function\n", " */\n", - " override fun doSomethingInAnObject(){\n", + " override fun doSomethingInAnObject() {\n", " println(\"I did it in an object\")\n", " }\n", "}\n", @@ -381,13 +396,14 @@ { "cell_type": "code", "source": [ - "fun doSomethingSpecial(){\n", + "fun doSomethingSpecial() {\n", " val base = \"base\"\n", " val special = \"special\"\n", + "\n", " /**\n", " * This one is inside another function\n", " */\n", - " fun String.doSomethingInside(){\n", + " fun String.doSomethingInside() {\n", " println(\"I did $special inside another function on $this\")\n", " }\n", " base.doSomethingInside()\n", @@ -415,12 +431,12 @@ "cell_type": "code", "source": [ "fun returnFunction(): (String) -> Unit {\n", - " fun printStringWithPrefix(str: String){\n", + " fun printStringWithPrefix(str: String) {\n", " println(\"Prefixed: $str\")\n", " }\n", " return ::printStringWithPrefix\n", " //return { printStringWithPrefix(it) }\n", - " // return { println(\"Prefixed: $it\") }\n", + " //return { println(\"Prefixed: $it\") }\n", "}\n", "\n", "returnFunction()(\"Haskel, Boo!\")" @@ -462,7 +478,6 @@ { "cell_type": "code", "source": [ - "\n", "fun returnUnit(): Unit {\n", " // no return statement `Unit` is returned implicitly\n", " val b = Unit\n", @@ -487,8 +502,8 @@ "metadata": {}, "cell_type": "code", "source": [ - "fun doNothing(){\n", - " \n", + "fun doNothing() {\n", + "\n", "}\n", "\n", "val a = doNothing()\n", @@ -520,9 +535,10 @@ "}\n", "\n", "doSomethingWithDefault()\n", + "doSomethingWithDefault(4)\n", "doSomethingWithDefault(2, \"aaa\")\n", "doSomethingWithDefault(b = \"fff\", a = 8)\n", - "doSomethingWithDefault(4, b = \"fff\")\n", + "doSomethingWithDefault(6, b = \"fff\")\n", "doSomethingWithDefault(a = 2, \"fff\")// don't do that" ], "metadata": { @@ -557,7 +573,7 @@ " sum += function(pos)\n", " pos += step\n", " }\n", - " return sum*step\n", + " return sum * step\n", "}\n", "\n", "integrate { x ->\n", @@ -585,13 +601,13 @@ "metadata": {}, "cell_type": "code", "source": [ - "fun functionWithParameters(){\n", + "fun functionWithParameters() {\n", " println(\"without default\")\n", "}\n", "\n", "//@JvmOverloads\n", "@JvmName(\"functionWithDefaultParameters\")\n", - "fun functionWithParameters(a: Int = 2){\n", + "fun functionWithParameters(a: Int = 2) { // don't do that\n", " println(\"with default\")\n", "}\n", "\n", @@ -622,7 +638,7 @@ "\n", "class Context(val a: String, val b: String)\n", "\n", - "fun somethingWith(context: Context) = with(context){\n", + "fun somethingWith(context: Context) = with(context) {\n", " println(a + b)\n", "}" ], @@ -661,25 +677,25 @@ { "cell_type": "code", "source": [ - "data class BuildResult internal constructor(val str: String, val int: Int, val optional: Double?){\n", - " init{\n", - " require(optional!= null){ \"null!\" }\n", + "data class BuildResult internal constructor(val str: String, val int: Int, val optional: Double?) {\n", + " init {\n", + " require(optional != null) { \"null!\" }\n", " }\n", "}\n", "\n", "class Builder(\n", - " var str: String = \"\", \n", + " var str: String = \"\",\n", " var int: Int = 0\n", - "){\n", + ") {\n", " var optional: Double? = null\n", "\n", " fun build() = BuildResult(str, int, optional)\n", "}\n", "\n", - "fun BuildResult(defaultInt: Int, block: Builder.() -> Unit): BuildResult = \n", + "fun BuildResult(defaultInt: Int, block: Builder.() -> Unit): BuildResult =\n", " Builder(int = defaultInt).apply(block).build()\n", "\n", - "val res = BuildResult(2){\n", + "val res = BuildResult(2) {\n", " str = \"ff\"\n", " optional = 1.0\n", "}\n", @@ -717,16 +733,19 @@ "source": [ "//Interfaces and objects\n", "\n", - "interface AnInterface {\n", + "fun interface AnInterface {\n", " val a: Int\n", " get() = 4\n", - " // set(value){\n", - " // println(value)\n", - " // }\n", + "\n", + " // set(value){\n", + " // println(value)\n", + " // }\n", " fun doSomething() //= println(\"From interface\")\n", + "\n", + " fun doSomething2() = Unit\n", "}\n", "\n", - "abstract class AnAbstractClass(override val a: Int): AnInterface{\n", + "abstract class AnAbstractClass(override val a: Int) : AnInterface {\n", " override final fun doSomething() = println(\"From a class\")\n", " abstract fun doSomethingElse()\n", "}\n", @@ -747,25 +766,30 @@ "}\n", "\n", "/**\n", - "* Creating an instance\n", - "*/\n", + " * Creating an instance\n", + " */\n", "val instance = AClass(3)\n", "\n", "/**\n", - "* Using singleton reference without constructor invocation\n", - "*/\n", + " * Using singleton reference without constructor invocation\n", + " */\n", "val obj: AnInterface = AnObject\n", "\n", "/**\n", - "* Anonymous object\n", - "*/\n", + " * Anonymous object\n", + " */\n", "val anonymous = object : AnInterface {\n", " override fun doSomething(): Unit = TODO(\"Not yet implemented\")\n", + " override fun doSomething2(): Unit = TODO(\"Not yet implemented\")\n", + "}\n", + "\n", + "val anonymous2 = AnInterface {\n", + " println(\"Do something\")\n", "}\n", "\n", "/**\n", - "* The one that should not be named\n", - "*/\n", + " * The one that should not be named\n", + " */\n", "val voldemort = object {\n", " fun doSomething(): Unit = TODO()\n", "}\n", @@ -787,23 +811,23 @@ "metadata": {}, "cell_type": "code", "source": [ - "fun interface Float64Function: (Double) -> Double {\n", + "fun interface Float64Function : (Double) -> Double {\n", " override operator fun invoke(arg: Double): Double\n", - " \n", - " operator fun invoke(doubles: DoubleArray): DoubleArray = DoubleArray(doubles.size){ invoke( doubles[it]) }\n", + "\n", + " operator fun invoke(doubles: DoubleArray): DoubleArray = DoubleArray(doubles.size) { invoke(doubles[it]) }\n", "}\n", "\n", - "val sin = object : Float64Function{\n", + "val sin = object : Float64Function {\n", " override fun invoke(p1: Double): Double = sin(p1)\n", "}\n", "\n", - "val cos = Float64Function{ kotlin.math.cos(it) }\n", + "val cos = Float64Function { kotlin.math.cos(it) }\n", "\n", "val tg = Float64Function(::tan)\n", "\n", - "sin(PI/2)\n", + "sin(PI / 2)\n", "\n", - "sin(doubleArrayOf(0.0, PI/2))" + "sin(doubleArrayOf(0.0, PI / 2))" ], "outputs": [], "execution_count": null @@ -828,15 +852,15 @@ { "cell_type": "code", "source": [ - "interface Producer{\n", + "interface Producer {\n", " fun produce(): T\n", "}\n", "\n", - "interface Consumer{\n", + "interface Consumer {\n", " fun consume(value: T)\n", "}\n", "\n", - "interface Doer: Producer, Consumer {\n", + "interface Doer : Producer, Consumer {\n", "\n", "}" ], @@ -924,7 +948,7 @@ " is String -> println(\"I am a String. Length is ${arg.length}\")\n", " is Int -> println(\"I am an Int.\")\n", " is Double -> println(\"I am a Double\")\n", - " // 2==2 -> println(\"Wat?\")\n", + " //2==2 -> println(\"Wat?\")\n", " else -> println(\"I don't know who am I?\")\n", "}\n", "\n", @@ -994,8 +1018,7 @@ { "cell_type": "code", "source": [ - "\n", - "val res: Result = runCatching { \n", + "val res: Result = runCatching {\n", " //error(\"Error happened\")\n", " 4\n", "}\n", @@ -1098,6 +1121,19 @@ "outputs": [], "execution_count": null }, + { + "metadata": {}, + "cell_type": "code", + "source": [ + "fun loop(block: () -> Unit): Nothing {\n", + " while (true) {\n", + " block()\n", + " }\n", + "}" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "source": [ @@ -1116,13 +1152,16 @@ { "cell_type": "code", "source": [ - "\n", - "class SimpleClass(val a: Int, val b: Double, c: Double){\n", + "class SimpleClass(val a: Int, val b: Double, c: Double) {\n", " override fun toString() = \"SimpleClass(a=$a, b=$b)\"\n", "}\n", "\n", "\n", "data class DataClass(val a: Int, var b: Double /*, d: Double */) {\n", + " init {\n", + " require(b >= 0) { \"B should be positive\" }\n", + " }\n", + "\n", " val c get() = b + 1\n", "}\n", "\n", @@ -1205,9 +1244,9 @@ "import java.util.Optional\n", "import kotlin.reflect.typeOf\n", "\n", - "println(typeOf>() == typeOf>>())\n", + "println(typeOf>() == typeOf>>())\n", "\n", - "println( typeOf() == typeOf()) " + "println(typeOf() == typeOf())" ], "outputs": [], "execution_count": null @@ -1215,7 +1254,7 @@ { "metadata": {}, "cell_type": "code", - "source": "mapOf().get(\"f\")!!", + "source": "mapOf().get(\"f\")!!", "outputs": [], "execution_count": null }, @@ -1237,6 +1276,7 @@ { "cell_type": "code", "source": [ + "import java.io.File\n", "\n", "/**\n", " * Safe call and elvis operator\n", @@ -1311,7 +1351,6 @@ { "cell_type": "code", "source": [ - "\n", "/**\n", " * Dart-like (?=) nullable assignment\n", " */\n", @@ -1382,10 +1421,10 @@ { "cell_type": "code", "source": [ - "infix fun > ClosedRange.intersect(other: ClosedRange): ClosedRange?{\n", + "infix fun > ClosedRange.intersect(other: ClosedRange): ClosedRange? {\n", " val start = maxOf(this.start, other.start)\n", " val end = minOf(this.endInclusive, other.endInclusive)\n", - " return if(end>=start) start..end else null\n", + " return if (end >= start) start..end else null\n", "}\n", "\n", "(0..8).intersect(6..12)\n", @@ -1405,7 +1444,7 @@ { "metadata": {}, "cell_type": "code", - "source": "", + "source": "0.0..8.0 intersect 2.9..6.1", "outputs": [], "execution_count": null }, @@ -1413,8 +1452,8 @@ "cell_type": "code", "source": [ "fun List.concat() = joinToString(separator = \"\")\n", - "listOf(\"a\",\"b\",\"c\").concat()\n", - "listOf(1,2,3).concat()" + "listOf(\"a\", \"b\", \"c\").concat()\n", + "listOf(1, 2, 3).concat()" ], "metadata": { "datalore": { @@ -1438,7 +1477,7 @@ "metadata": {}, "cell_type": "code", "source": [ - "val functionWithReciever: List.(arg: Int) -> Unit = {arg->\n", + "val functionWithReciever: List.(arg: Int) -> Unit = { arg ->\n", " println(get(arg))\n", "}\n", "\n", @@ -1467,13 +1506,12 @@ { "cell_type": "code", "source": [ - "\n", "/**\n", " * Extension property (must be virtual)\n", " */\n", "val List.odd get() = filter { it.toInt() % 2 == 1 }\n", "\n", - "List(10){it}.odd" + "List(10) { it }.odd" ], "metadata": { "datalore": { @@ -1491,15 +1529,22 @@ "source": [ "var MutableMap.a: String?\n", " get() = this.get(\"a\")\n", - " set(value){\n", - " if(value == null){\n", + " set(value) {\n", + " if (value == null) {\n", " this.remove(\"a\")\n", " } else {\n", - " this.set(\"a\",value)\n", + " this.set(\"a\", value)\n", " }\n", " }\n", "\n", - "val map = mutableMapOf(\"a\" to \"a\", \"b\" to \"b\")\n", + "val map = mutableMapOf(\n", + " \"a\" to \"a\",\n", + " \"b\" to \"b\"\n", + ")\n", + "val map2 = mutableMapOf(\n", + " Pair(\"a\", \"a\"),\n", + " Pair(\"b\", \"b\")\n", + ")\n", "\n", "map.a = \"6\"\n", "\n", @@ -1519,7 +1564,6 @@ { "cell_type": "code", "source": [ - "\n", "/**\n", " * Extension variable (also must be virtual)\n", " */\n", @@ -1530,7 +1574,7 @@ " }\n", "\n", "\n", - "val array = Array(5){it}\n", + "val array = Array(5) { it }\n", "array.second = 9\n", "array" ], @@ -1563,7 +1607,7 @@ { "cell_type": "code", "source": [ - "object AClass{\n", + "object AClass {\n", " val a = \"a\"\n", " val b = \"b\"\n", " val c = \"c\"\n", @@ -1580,7 +1624,7 @@ "println(\"a = ${AClass.a}, b = ${AClass.b}, c = ${AClass.c}\")\n", "\n", "// Using `with`\n", - "val res = with(AClass){\n", + "val res = with(AClass) {\n", " // AClass type is the receiver in this scope\n", " println(\"a = ${this.a}, b = $b, c = $c\")\n", " /*return@with*/ \"some value\"\n", @@ -1603,11 +1647,11 @@ "metadata": {}, "cell_type": "code", "source": [ - "object AContext{\n", + "object AContext {\n", " fun AClass.abc() = a + b + c // warning additional concatenation\n", "}\n", "\n", - "fun printAbc(aClass: AClass) = with(AContext){\n", + "fun printAbc(aClass: AClass) = with(AContext) {\n", " aClass.abc()\n", "}" ], @@ -1617,7 +1661,6 @@ { "cell_type": "code", "source": [ - "\n", "//using `run`\n", "getAClass()?.takeIf { it.a.isNotEmpty() }?.run {\n", " // the same as above\n", @@ -1626,7 +1669,7 @@ "}\n", "\n", "val runResult: Int = run {\n", - " \n", + "\n", "}\n", "\n", "//Using `let` to compose result. Not recommended using without a need\n", @@ -1650,7 +1693,15 @@ "cell_type": "code", "source": [ "//Don't do that\n", - "fun scopeAbuse(str: String?) = str.takeIf { it?.isNotEmpty() == true }?.let { it.substring(0..4) }?.let { it.matches(\".*\".toRegex())}" + "fun scopeAbuse(str: String?) =\n", + " str.takeIf { it?.isNotEmpty() == true }?.let { it.substring(0..4) }?.let { it.matches(\".*\".toRegex()) }\n", + "\n", + "fun withoutAbuse(str: String?): Boolean? = if (str?.isNotEmpty() == true) {\n", + " val substring = str.substring(0..4)\n", + " substring.matches(\".*\".toRegex())\n", + "} else {\n", + " null\n", + "}" ], "outputs": [], "execution_count": null @@ -1679,10 +1730,14 @@ "var i = 2\n", "\n", "/**\n", - "* [also] block does not affect the result\n", - "*/\n", + " * [also] block does not affect the result\n", + " */\n", "fun getAndIncrement() = i.also { i += 1 } //don't do that\n", "\n", + "fun incrementAndPring(arg: Int) = (arg + 1).also{\n", + " println(it)\n", + "}\n", + "\n", "println(getAndIncrement())\n", "println(i)" ], @@ -1700,7 +1755,6 @@ { "cell_type": "code", "source": [ - "\n", "class Rectangle {\n", " var length: Number = 0\n", " var breadth: Number = 0\n", @@ -1708,9 +1762,9 @@ "}\n", "\n", "/**\n", - " * Configure properties of an object (apply)\n", - " * https://kotlinlang.org/docs/idioms.html#configure-properties-of-an-object-apply\n", - " */\n", + " * Configure properties of an object (apply)\n", + " * https://kotlinlang.org/docs/idioms.html#configure-properties-of-an-object-apply\n", + " */\n", "val myRectangle = Rectangle().apply {\n", " length = 4\n", " breadth = 5\n", @@ -1740,6 +1794,13 @@ "outputs": [], "execution_count": null }, + { + "metadata": {}, + "cell_type": "code", + "source": "", + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "source": [ @@ -1790,10 +1851,9 @@ { "cell_type": "code", "source": [ - "\n", "/**\n", - "* This one creates a mutable list\n", - "*/\n", + " * This one creates a mutable list\n", + " */\n", "val mutableList: MutableList = mutableListOf(\"a\", \"b\", \"c\")\n", "mutableList[2] = \"d\"\n", "mutableList.add(\"e\")\n", @@ -1815,7 +1875,6 @@ "metadata": {}, "cell_type": "code", "source": [ - "\n", "//don't do that ever\n", "fun doBadThingWithList(list: List): List = (list as MutableList).apply { add(\"something\") }\n", "\n", @@ -1844,9 +1903,9 @@ "metadata": {}, "cell_type": "code", "source": [ - "val mutableList = mutableListOf(1,2,3)\n", + "val mutableList = mutableListOf(1, 2, 3)\n", "\n", - "fun consumeList(list: List){\n", + "fun consumeList(list: List) {\n", " println(list.joinToString())\n", "}\n", "consumeList(mutableList)\n", @@ -1859,7 +1918,7 @@ { "metadata": {}, "cell_type": "code", - "source": "listOf(1,2) + listOf(3,4)", + "source": "listOf(1, 2) + listOf(3, 4)", "outputs": [], "execution_count": null }, @@ -1895,7 +1954,6 @@ { "cell_type": "code", "source": [ - "\n", "/**\n", " * This one creates a mutable ArrayList.\n", " */\n", @@ -1923,10 +1981,9 @@ { "cell_type": "code", "source": [ - "\n", "//Bonus\n", "\n", - "val lambdaList = List(3){ it.toString() }\n", + "val lambdaList = List(3) { it.toString() }\n", "println(lambdaList)\n", "\n", "val builderList: List = buildList {\n", @@ -1934,6 +1991,7 @@ " add(8)\n", " remove(8)\n", "}\n", + "\n", "builderList" ], "metadata": { @@ -1985,11 +2043,11 @@ "/**\n", " * Use shortcut function to provide default values\n", " */\n", - "fun doSomething(additionalArguments: List = emptyList()){\n", + "fun doSomething(additionalArguments: List = emptyList()) {\n", " TODO()\n", " emptyArray()\n", " emptySet()\n", - " emptyMap()\n", + " emptyMap()\n", "}\n", "emptyList()::class" ], @@ -2055,14 +2113,13 @@ { "cell_type": "code", "source": [ - "\n", "//val entry: MutableMap.MutableEntry = map.iterator().next()\n", "\n", "//map.entries.first().component2()\n", "\n", "/**\n", - " * The destructuring declaration for maps and other objects that support `operator fun componentN`\n", - " */\n", + " * The destructuring declaration for maps and other objects that support `operator fun componentN`\n", + " */\n", "for ((k: String, v) in map) {\n", "//val (k, v) = entry\n", "// val k = entry.component1()\n", @@ -2083,7 +2140,12 @@ }, { "cell_type": "code", - "source": "map.forEach { (k, v) -> println(\"$k -> $v\")}", + "source": [ + "map.forEach { (k, v) -> println(\"$k -> $v\") }\n", + "\n", + "// java version\n", + "map.forEach { k, v -> println(\"$k -> $v\") }" + ], "metadata": { "datalore": { "node_id": "s1Q65aNWb9YNBZOgxmjotW", @@ -2098,12 +2160,11 @@ { "cell_type": "code", "source": [ - "\n", "val (a, b) = Pair(1, 2)\n", "\n", "val coord = doubleArrayOf(0.0, 1.0, 2.0)\n", "\n", - "val (x,y,z) = coord\n", + "val (x, y, z) = coord\n", "\n", "data class Coordinate(val x: Double, val y: Int)\n", "\n", @@ -2140,25 +2201,24 @@ { "cell_type": "code", "source": [ - "class AClassWithList{\n", + "class AClassWithList {\n", " var b: Double = 2.0\n", " private set\n", "\n", - " init{\n", + " init {\n", " b = 5.0\n", " }\n", "\n", " private val _list: MutableList = ArrayList()\n", " val list: List get() = _list\n", - " \n", - " fun add(int: Int){\n", - " require(int>0)\n", + "\n", + " fun add(int: Int) {\n", + " require(int > 0)\n", " _list.add(int)\n", " }\n", "}\n", "\n", "\n", - "\n", "val obj = AClassWithList()\n", "\n", "// obj.b = 10.0 //error\n", @@ -2178,9 +2238,7 @@ }, { "cell_type": "markdown", - "source": [ - "## Wrap mutable logic" - ], + "source": "## Wrap mutable logic / Kotlin builder pattern", "attachments": {}, "metadata": { "datalore": { @@ -2195,7 +2253,7 @@ "cell_type": "code", "source": [ "val list = buildList {\n", - " repeat(10){\n", + " repeat(10) {\n", " add(it)\n", " }\n", "}\n", @@ -2222,11 +2280,11 @@ " var a: String = a\n", " var b: String = \"\"\n", " var c = 0\n", - " \n", + "\n", " fun build() = ImmutableObject(a, b, c)\n", "}\n", "\n", - "fun ImmutableObject(a: String, block: ImmutableObjectBuilder.() -> Unit): ImmutableObject =\n", + "/*inline*/ fun ImmutableObject(a: String, block: ImmutableObjectBuilder.() -> Unit): ImmutableObject =\n", " ImmutableObjectBuilder(a).apply(block).build()\n", "\n", "ImmutableObject(\"aValue\") {\n", @@ -2259,7 +2317,6 @@ }, "cell_type": "code", "source": [ - "\n", "val emailsList = emptyList()\n", "\n", "// When used directly infix in operator checks if the element is contained in a collection\n", @@ -2310,7 +2367,6 @@ }, "cell_type": "code", "source": [ - "\n", "// Another (different) use of `in` is iteration over range or collection using\n", "// using `operator fun iterator`\n", "\n", @@ -2322,7 +2378,7 @@ " println(i)\n", "} //the same, but with boxing\n", "\n", - "for (i in 1..<100) {\n", + "for (i in 1 ..< 100) {\n", " println(i)\n", "} // half-open range: does not include 100\n", "\n", @@ -2345,7 +2401,7 @@ " }\n", "}\n", "\n", - "for (x in 0.0..10.0 step 0.5){\n", + "for (x in 0.0..10.0 step 0.5) {\n", " println(x)\n", "}" ], @@ -2385,6 +2441,7 @@ " //.onEach { println(it) }\n", " //.sumOf { it } //use one of reduce operations\n", " .reduce { acc: Int, i: Int -> acc + i }\n", + " //.fold(0.0) { acc: Double, i: Int -> acc + i }\n", "\n", "result" ], @@ -2404,7 +2461,7 @@ "source": [ "val sequence = sequence {\n", " var counter = 1\n", - " while(true){\n", + " while (true) {\n", " yield(counter++)\n", " yield(counter++)\n", " // println(counter)\n", @@ -2485,7 +2542,7 @@ "}\n", "\n", "data class IntContainer(val arg: Int) {\n", - " \n", + "\n", " companion object : Factory {\n", " override fun build(str: String) = IntContainer(str.toInt())\n", "\n", @@ -2494,7 +2551,7 @@ "}\n", "\n", "data class DoubleContainer(val arg: Double) {\n", - " \n", + "\n", " companion object : Factory {\n", " override fun build(str: String) = DoubleContainer(str.toDouble())\n", " }\n", @@ -2534,8 +2591,7 @@ { "cell_type": "code", "source": [ - "\n", - "open class Bad{\n", + "open class Bad {\n", " val value: Int = requestValue()\n", "\n", " open fun requestValue(): Int {\n", @@ -2543,7 +2599,7 @@ " return 2\n", " }\n", "\n", - " private fun doSomethingElse(){\n", + " private fun doSomethingElse() {\n", " println(value)\n", " }\n", "}\n", @@ -2565,7 +2621,7 @@ "metadata": {}, "cell_type": "code", "source": [ - "class BadString{\n", + "class BadString {\n", " val value: String = requestValue()\n", "\n", " fun requestValue(): String {\n", @@ -2573,7 +2629,7 @@ " return \"2\"\n", " }\n", "\n", - " private fun doSomethingElse(){\n", + " private fun doSomethingElse() {\n", " println(value)\n", " }\n", "}\n", @@ -2586,11 +2642,9 @@ { "cell_type": "code", "source": [ - "\n", - "\n", "//Factory functions are preferred to the initialization logic\n", "\n", - "data class Good internal constructor(val value: Int){\n", + "data class Good internal constructor(val value: Int) {\n", " init {\n", " //Initialization block is there to check arguments\n", " require(value >= 0)\n", @@ -2599,11 +2653,10 @@ " companion object\n", "}\n", "\n", - "fun requestValue(): Int = TODO()\n", + "private fun requestValue(): Int = TODO()\n", "\n", "// This is the factory-function\n", - "fun Good() = Good(requestValue())\n", - "\n", + "fun Good(): Good = Good(requestValue())\n", "\n", "// additional constructor-like builders could be added to the companion\n", "\n", @@ -2641,7 +2694,7 @@ { "cell_type": "code", "source": [ - "class ClassWithALazyProperty{\n", + "class ClassWithALazyProperty {\n", " //Use lazy delegate for something that should be calculated ones on first call\n", " val lazyValue by lazy {\n", " //Do dome heavy logic here\n", @@ -2649,16 +2702,18 @@ " 22\n", " }\n", "\n", - " val getterValue: Int get(){\n", - " println(\"got\")\n", - " return 33\n", - " }\n", + " val getterValue: Int\n", + " get() {\n", + " println(\"got\")\n", + " return 33\n", + " }\n", "}\n", + "\n", "val lazyClass = ClassWithALazyProperty()\n", - "lazyClass.lazyValue\n", - "lazyClass.lazyValue\n", - "lazyClass.getterValue\n", - "lazyClass.getterValue" + "println(lazyClass.lazyValue)\n", + "println(lazyClass.lazyValue)\n", + "println(lazyClass.getterValue)\n", + "println(lazyClass.getterValue)" ], "metadata": { "datalore": { @@ -2674,7 +2729,6 @@ { "cell_type": "code", "source": [ - "\n", "//Using other delegates\n", "val map = mutableMapOf(\"a\" to 1, \"b\" to 2)\n", "\n", @@ -2713,7 +2767,6 @@ { "cell_type": "code", "source": [ - "\n", "/**\n", " * Definition of inline function\n", " */\n", @@ -2749,7 +2802,6 @@ { "cell_type": "code", "source": [ - "\n", "/**\n", " * Using inline function for type reification during the compile time\n", " */\n", diff --git a/notebooks/Multitasking.ipynb b/notebooks/Multitasking.ipynb index 3278a8e..7f014cb 100644 --- a/notebooks/Multitasking.ipynb +++ b/notebooks/Multitasking.ipynb @@ -2,7 +2,6 @@ "cells": [ { "cell_type": "code", - "execution_count": null, "metadata": { "datalore": { "hide_input_from_viewers": true, @@ -11,10 +10,11 @@ "type": "CODE" } }, - "outputs": [], "source": [ "%use coroutines" - ] + ], + "outputs": [], + "execution_count": null }, { "cell_type": "markdown", @@ -40,7 +40,6 @@ }, { "cell_type": "code", - "execution_count": null, "metadata": { "datalore": { "hide_input_from_viewers": true, @@ -49,16 +48,16 @@ "type": "CODE" } }, - "outputs": [], "source": [ "repeat(10){\n", " println(\"Line number $it\")\n", "}" - ] + ], + "outputs": [], + "execution_count": null }, { "cell_type": "code", - "execution_count": null, "metadata": { "datalore": { "hide_input_from_viewers": true, @@ -67,12 +66,13 @@ "type": "CODE" } }, - "outputs": [], "source": [ "import java.util.stream.*\n", "\n", "IntStream.range(0, 100).sum()" - ] + ], + "outputs": [], + "execution_count": null }, { "attachments": {}, @@ -91,7 +91,6 @@ }, { "cell_type": "code", - "execution_count": 1, "metadata": { "datalore": { "hide_input_from_viewers": true, @@ -100,64 +99,18 @@ "type": "CODE" } }, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "null\n", - "java.util.ConcurrentModificationException\n", - "\tat java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1095)\n", - "\tat java.base/java.util.ArrayList$Itr.next(ArrayList.java:1049)\n", - "\tat Line_0_jupyter.(Line_0.jupyter.kts:6)\n", - "\tat java.base/jdk.internal.reflect.DirectConstructorHandleAccessor.newInstance(DirectConstructorHandleAccessor.java:62)\n", - "\tat java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:502)\n", - "\tat java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:486)\n", - "\tat kotlin.script.experimental.jvm.BasicJvmScriptEvaluator.evalWithConfigAndOtherScriptsResults(BasicJvmScriptEvaluator.kt:122)\n", - "\tat kotlin.script.experimental.jvm.BasicJvmScriptEvaluator.invoke$suspendImpl(BasicJvmScriptEvaluator.kt:48)\n", - "\tat kotlin.script.experimental.jvm.BasicJvmScriptEvaluator.invoke(BasicJvmScriptEvaluator.kt)\n", - "\tat kotlin.script.experimental.jvm.BasicJvmReplEvaluator.eval(BasicJvmReplEvaluator.kt:49)\n", - "\tat org.jetbrains.kotlinx.jupyter.repl.impl.InternalEvaluatorImpl$eval$resultWithDiagnostics$1.invokeSuspend(InternalEvaluatorImpl.kt:127)\n", - "\tat kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)\n", - "\tat kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:104)\n", - "\tat kotlinx.coroutines.EventLoopImplBase.processNextEvent(EventLoop.common.kt:277)\n", - "\tat kotlinx.coroutines.BlockingCoroutine.joinBlocking(Builders.kt:95)\n", - "\tat kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking(Builders.kt:69)\n", - "\tat kotlinx.coroutines.BuildersKt.runBlocking(Unknown Source)\n", - "\tat kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking$default(Builders.kt:48)\n", - "\tat kotlinx.coroutines.BuildersKt.runBlocking$default(Unknown Source)\n", - "\tat org.jetbrains.kotlinx.jupyter.repl.impl.InternalEvaluatorImpl.eval(InternalEvaluatorImpl.kt:127)\n", - "\tat org.jetbrains.kotlinx.jupyter.repl.impl.CellExecutorImpl$execute$1$result$1.invoke(CellExecutorImpl.kt:79)\n", - "\tat org.jetbrains.kotlinx.jupyter.repl.impl.CellExecutorImpl$execute$1$result$1.invoke(CellExecutorImpl.kt:77)\n", - "\tat org.jetbrains.kotlinx.jupyter.repl.impl.ReplForJupyterImpl.withHost(ReplForJupyterImpl.kt:758)\n", - "\tat org.jetbrains.kotlinx.jupyter.repl.impl.CellExecutorImpl.execute(CellExecutorImpl.kt:77)\n", - "\tat org.jetbrains.kotlinx.jupyter.repl.execution.CellExecutor$DefaultImpls.execute$default(CellExecutor.kt:12)\n", - "\tat org.jetbrains.kotlinx.jupyter.repl.impl.ReplForJupyterImpl.evaluateUserCode(ReplForJupyterImpl.kt:581)\n", - "\tat org.jetbrains.kotlinx.jupyter.repl.impl.ReplForJupyterImpl.access$evaluateUserCode(ReplForJupyterImpl.kt:136)\n", - "\tat org.jetbrains.kotlinx.jupyter.repl.impl.ReplForJupyterImpl$evalEx$1.invoke(ReplForJupyterImpl.kt:439)\n", - "\tat org.jetbrains.kotlinx.jupyter.repl.impl.ReplForJupyterImpl$evalEx$1.invoke(ReplForJupyterImpl.kt:436)\n", - "\tat org.jetbrains.kotlinx.jupyter.repl.impl.ReplForJupyterImpl.withEvalContext(ReplForJupyterImpl.kt:417)\n", - "\tat org.jetbrains.kotlinx.jupyter.repl.impl.ReplForJupyterImpl.evalEx(ReplForJupyterImpl.kt:436)\n", - "\tat org.jetbrains.kotlinx.jupyter.messaging.IdeCompatibleMessageRequestProcessor$processExecuteRequest$1$response$1$1.invoke(IdeCompatibleMessageRequestProcessor.kt:140)\n", - "\tat org.jetbrains.kotlinx.jupyter.messaging.IdeCompatibleMessageRequestProcessor$processExecuteRequest$1$response$1$1.invoke(IdeCompatibleMessageRequestProcessor.kt:139)\n", - "\tat org.jetbrains.kotlinx.jupyter.execution.JupyterExecutorImpl$Task.execute(JupyterExecutorImpl.kt:42)\n", - "\tat org.jetbrains.kotlinx.jupyter.execution.JupyterExecutorImpl$executorThread$1.invoke(JupyterExecutorImpl.kt:82)\n", - "\tat org.jetbrains.kotlinx.jupyter.execution.JupyterExecutorImpl$executorThread$1.invoke(JupyterExecutorImpl.kt:80)\n", - "\tat kotlin.concurrent.ThreadsKt$thread$thread$1.run(Thread.kt:30)\n" - ] - } - ], "source": [ "val list = (0..100).toMutableList()\n", "\n", "list.forEach {\n", " if(it % 2 == 0) list.remove(it)\n", "}" - ] + ], + "outputs": [], + "execution_count": null }, { "cell_type": "code", - "execution_count": null, "metadata": { "datalore": { "hide_input_from_viewers": true, @@ -166,8 +119,9 @@ "type": "CODE" } }, + "source": [], "outputs": [], - "source": [] + "execution_count": null }, { "attachments": {}, @@ -186,7 +140,6 @@ }, { "cell_type": "code", - "execution_count": null, "metadata": { "datalore": { "hide_input_from_viewers": true, @@ -195,16 +148,16 @@ "type": "CODE" } }, - "outputs": [], "source": [ "val sum = IntStream.range(0, 100).parallel().sum()\n", "\n", "println(sum)" - ] + ], + "outputs": [], + "execution_count": null }, { "cell_type": "code", - "execution_count": null, "metadata": { "datalore": { "hide_input_from_viewers": true, @@ -213,8 +166,9 @@ "type": "CODE" } }, + "source": [], "outputs": [], - "source": [] + "execution_count": null }, { "attachments": {}, @@ -233,7 +187,6 @@ }, { "cell_type": "code", - "execution_count": null, "metadata": { "datalore": { "hide_input_from_viewers": true, @@ -242,18 +195,18 @@ "type": "CODE" } }, - "outputs": [], "source": [ "fun runLongTask(result: Int = 8): Int {\n", " Thread.sleep(100)\n", " println(\"Task complete: $result\")\n", " return result\n", "}" - ] + ], + "outputs": [], + "execution_count": null }, { "cell_type": "code", - "execution_count": null, "metadata": { "datalore": { "hide_input_from_viewers": true, @@ -262,7 +215,6 @@ "type": "CODE" } }, - "outputs": [], "source": [ "import java.util.concurrent.*\n", "\n", @@ -275,7 +227,9 @@ "}\n", "\n", "future.get()" - ] + ], + "outputs": [], + "execution_count": null }, { "attachments": {}, @@ -294,7 +248,6 @@ }, { "cell_type": "code", - "execution_count": null, "metadata": { "datalore": { "hide_input_from_viewers": true, @@ -303,18 +256,18 @@ "type": "CODE" } }, - "outputs": [], "source": [ "interface Observable{\n", " fun onChange(callback: (Int) -> Unit)\n", "}\n", "\n", "val observable: Observable by lazy{ TODO() }" - ] + ], + "outputs": [], + "execution_count": null }, { "cell_type": "code", - "execution_count": null, "metadata": { "datalore": { "hide_input_from_viewers": true, @@ -323,14 +276,15 @@ "type": "CODE" } }, - "outputs": [], "source": [ "val list: MutableList = mutableListOf()\n", "\n", "observable.onChange { \n", " list.add(it)\n", "}" - ] + ], + "outputs": [], + "execution_count": null }, { "attachments": {}, @@ -349,7 +303,6 @@ }, { "cell_type": "code", - "execution_count": null, "metadata": { "datalore": { "hide_input_from_viewers": true, @@ -358,12 +311,12 @@ "type": "CODE" } }, + "source": [], "outputs": [], - "source": [] + "execution_count": null }, { "cell_type": "code", - "execution_count": null, "metadata": { "datalore": { "hide_input_from_viewers": true, @@ -372,7 +325,6 @@ "type": "CODE" } }, - "outputs": [], "source": [ "val executor: ExecutorService = Executors.newFixedThreadPool(4)\n", "\n", @@ -381,7 +333,9 @@ " runLongTask(it)\n", " }\n", "}" - ] + ], + "outputs": [], + "execution_count": null }, { "attachments": {}, @@ -400,7 +354,6 @@ }, { "cell_type": "code", - "execution_count": null, "metadata": { "datalore": { "hide_input_from_viewers": true, @@ -409,7 +362,6 @@ "type": "CODE" } }, - "outputs": [], "source": [ "import kotlin.io.path.Path\n", "import kotlin.io.path.writeText\n", @@ -423,7 +375,9 @@ " .forEach { \n", " file.writeText(it)\n", " }" - ] + ], + "outputs": [], + "execution_count": null }, { "attachments": {}, @@ -442,7 +396,6 @@ }, { "cell_type": "code", - "execution_count": null, "metadata": { "datalore": { "hide_input_from_viewers": true, @@ -451,7 +404,6 @@ "type": "CODE" } }, - "outputs": [], "source": [ "val cache = mutableMapOf\n", "\n", @@ -466,7 +418,9 @@ " consumer(result)\n", " }\n", "}" - ] + ], + "outputs": [], + "execution_count": null }, { "attachments": {}, @@ -500,7 +454,6 @@ }, { "cell_type": "code", - "execution_count": null, "metadata": { "datalore": { "hide_input_from_viewers": true, @@ -509,7 +462,6 @@ "type": "CODE" } }, - "outputs": [], "source": [ "import kotlin.concurrent.*\n", "\n", @@ -517,11 +469,12 @@ " runLongTask()\n", "}\n", "t.join()" - ] + ], + "outputs": [], + "execution_count": null }, { "cell_type": "code", - "execution_count": null, "metadata": { "datalore": { "hide_input_from_viewers": true, @@ -530,8 +483,9 @@ "type": "CODE" } }, + "source": [], "outputs": [], - "source": [] + "execution_count": null }, { "attachments": {}, @@ -550,7 +504,6 @@ }, { "cell_type": "code", - "execution_count": null, "metadata": { "datalore": { "hide_input_from_viewers": true, @@ -559,7 +512,6 @@ "type": "CODE" } }, - "outputs": [], "source": [ "val future = executor.submit{\n", " runLongTask()\n", @@ -567,7 +519,9 @@ "\n", "future.get()\n", "future.cancel(true)" - ] + ], + "outputs": [], + "execution_count": null }, { "attachments": {}, @@ -586,7 +540,6 @@ }, { "cell_type": "code", - "execution_count": null, "metadata": { "datalore": { "hide_input_from_viewers": true, @@ -595,7 +548,6 @@ "type": "CODE" } }, - "outputs": [], "source": [ "import java.util.concurrent.*\n", "\n", @@ -613,7 +565,9 @@ "\n", "cf2.join()\n", "cf3.join()" - ] + ], + "outputs": [], + "execution_count": null }, { "attachments": {}, @@ -632,7 +586,6 @@ }, { "cell_type": "code", - "execution_count": null, "metadata": { "datalore": { "hide_input_from_viewers": true, @@ -641,7 +594,6 @@ "type": "CODE" } }, - "outputs": [], "source": [ "import java.util.concurrent.locks.*\n", "\n", @@ -666,7 +618,9 @@ "cf5.join()\n", "\n", "list" - ] + ], + "outputs": [], + "execution_count": null }, { "cell_type": "markdown", @@ -677,9 +631,7 @@ }, { "cell_type": "code", - "execution_count": null, "metadata": {}, - "outputs": [], "source": [ "class A(val value: Int)\n", "class B(val value: Int)\n", @@ -690,7 +642,9 @@ "val combined = aFlow.zip(bFlow){ a, b->\n", " a.value + b.value\n", "}.debounce(2.seconds)" - ] + ], + "outputs": [], + "execution_count": null }, { "cell_type": "markdown", @@ -701,9 +655,7 @@ }, { "cell_type": "code", - "execution_count": null, "metadata": {}, - "outputs": [], "source": [ "sealed class Event {\n", " class Open(val transactionId: Int): Event()\n", @@ -732,7 +684,9 @@ " }\n", "\n", "}" - ] + ], + "outputs": [], + "execution_count": null }, { "attachments": {}, @@ -766,7 +720,6 @@ }, { "cell_type": "code", - "execution_count": null, "metadata": { "datalore": { "hide_input_from_viewers": true, @@ -775,7 +728,6 @@ "type": "CODE" } }, - "outputs": [], "source": [ "import java.net.*\n", "import java.net.http.*\n", @@ -807,7 +759,9 @@ " }\n", " .thenAccept{ println(it.toList()) }\n", " .join()" - ] + ], + "outputs": [], + "execution_count": null }, { "attachments": {}, @@ -826,7 +780,6 @@ }, { "cell_type": "code", - "execution_count": null, "metadata": { "datalore": { "hide_input_from_viewers": true, @@ -835,8 +788,9 @@ "type": "CODE" } }, + "source": [], "outputs": [], - "source": [] + "execution_count": null } ], "metadata": {