From 48806d06c88650d2c4e2a322bd01e6da48ef7a19 Mon Sep 17 00:00:00 2001 From: martin-schulte Date: Mon, 11 Mar 2019 16:05:39 +0100 Subject: [PATCH 01/95] chore: added //sampleStart & //sampleEnd (#76) --- examples/05_Collections/13_max.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/examples/05_Collections/13_max.md b/examples/05_Collections/13_max.md index e75f3bf..85dcf08 100755 --- a/examples/05_Collections/13_max.md +++ b/examples/05_Collections/13_max.md @@ -7,11 +7,13 @@ ```kotlin fun main() { +//sampleStart val numbers = listOf(1, 2, 3) val empty = emptyList() println("Numbers: $numbers, min = ${numbers.min()} max = ${numbers.max()}") // 1 println("Empty: $empty, min = ${empty.min()}, max = ${empty.max()}") // 2 +//sampleEnd } ``` From fb871be9c8523223442430560594b3f1bd2aee6a Mon Sep 17 00:00:00 2001 From: Guangyao Miao Date: Sun, 28 Apr 2019 06:15:03 -0400 Subject: [PATCH 02/95] refactor: add white spaces in comment (#78) --- examples/01_introduction/02_Functions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/01_introduction/02_Functions.md b/examples/01_introduction/02_Functions.md index 0bf3935..59858ac 100755 --- a/examples/01_introduction/02_Functions.md +++ b/examples/01_introduction/02_Functions.md @@ -9,7 +9,7 @@ fun printMessage(message: String): Unit { // 1 println(message) } -fun printMessageWithPrefix(message: String, prefix: String = "Info") { // 2 +fun printMessageWithPrefix(message: String, prefix: String = "Info") { // 2 println("[$prefix] $message") } From 4e95fee8312aba94d3abed72ae92e052307f27e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robin=20Br=C3=A4mer?= Date: Tue, 21 May 2019 14:29:12 +0200 Subject: [PATCH 03/95] docs: fix typo (#79) --- examples/02_control_flow/01_When.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/02_control_flow/01_When.md b/examples/02_control_flow/01_When.md index 627faf1..157f0a7 100755 --- a/examples/02_control_flow/01_When.md +++ b/examples/02_control_flow/01_When.md @@ -39,7 +39,7 @@ class MyClass Note that all branch conditions are checked sequentially until one of them is satisfied. So, only the first suitable branch will be executed. -## When Expresion +## When Expression
From bf24513b0c9e316da03c315bd47e54cb992fa00f Mon Sep 17 00:00:00 2001 From: Developer Davo Date: Tue, 28 May 2019 17:50:31 +0200 Subject: [PATCH 04/95] Update 01_When.md --- examples/02_control_flow/01_When.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/02_control_flow/01_When.md b/examples/02_control_flow/01_When.md index 157f0a7..1d51695 100755 --- a/examples/02_control_flow/01_When.md +++ b/examples/02_control_flow/01_When.md @@ -15,8 +15,8 @@ fun main() { cases("hello") } -fun cases(obj: Any) { // 1 - when (obj) { +fun cases(obj: Any) { + when (obj) { // 1 1 -> println("One") // 2 "Hello" -> println("Greeting") // 3 is Long -> println("Long") // 4 From 90097e75c67c6ef4409e51850a471fde11f729dc Mon Sep 17 00:00:00 2001 From: Jared Burrows Date: Sun, 2 Jun 2019 04:52:29 -0400 Subject: [PATCH 05/95] refactor: fix formatting on Map Element Access examples (#84) --- examples/05_Collections/15_Map_getValue.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/examples/05_Collections/15_Map_getValue.md b/examples/05_Collections/15_Map_getValue.md index 7fd8b10..c7e640e 100644 --- a/examples/05_Collections/15_Map_getValue.md +++ b/examples/05_Collections/15_Map_getValue.md @@ -23,8 +23,7 @@ fun main(args: Array) { try { map.getValue("anotherKey") // 4 - } - catch (e: NoSuchElementException) { + } catch (e: NoSuchElementException) { println("Message: $e") } From 7f83cd0678bd03bf20953c3a28ac6adc5d81a6ff Mon Sep 17 00:00:00 2001 From: Jared Burrows Date: Sun, 2 Jun 2019 04:53:05 -0400 Subject: [PATCH 06/95] refactor: fix formatting of Map examples (#83) --- examples/05_Collections/03_Map.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/05_Collections/03_Map.md b/examples/05_Collections/03_Map.md index 8a66c25..28f8013 100644 --- a/examples/05_Collections/03_Map.md +++ b/examples/05_Collections/03_Map.md @@ -20,7 +20,7 @@ fun updatePointsCredit(accountId: Int) { fun accountsReport() { println("EZ-Pass report:") - EZPassReport.forEach{ // 5 + EZPassReport.forEach { // 5 k, v -> println("ID $k: credit $v") } } @@ -44,4 +44,4 @@ fun main() { 6. Reads the account points balance, before updates. 7. Updates an existing account two times. 8. Tries to update a non-existing account: prints an error message. -9. Reads the account points balance, after updates. \ No newline at end of file +9. Reads the account points balance, after updates. From e75e7df122fd21a70bce84f96e62be00e37bb583 Mon Sep 17 00:00:00 2001 From: Jared Burrows Date: Sun, 2 Jun 2019 04:53:44 -0400 Subject: [PATCH 07/95] refactor: fix formatting (#82) --- examples/05_Collections/01_List.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/05_Collections/01_List.md b/examples/05_Collections/01_List.md index 85d6ac3..6119688 100644 --- a/examples/05_Collections/01_List.md +++ b/examples/05_Collections/01_List.md @@ -19,7 +19,7 @@ fun getSysSudoers(): List { // 4 fun main() { addSudoer(4) // 5 println("Tot sudoers: ${getSysSudoers().size}") // 6 - getSysSudoers().forEach{ // 7 + getSysSudoers().forEach { // 7 i -> println("Some useful info on user $i") } // getSysSudoers().add(5) <- Error! // 8 From 1314bd55d2491128bede88ab13ed23d274929d55 Mon Sep 17 00:00:00 2001 From: Prendota Date: Mon, 3 Jun 2019 16:02:40 +0300 Subject: [PATCH 08/95] docs: migrate to new syntax --- examples/09_Kotlin_JS/01_dynamic.md | 6 +----- examples/09_Kotlin_JS/02_js_function.md | 11 ++--------- examples/09_Kotlin_JS/03_external.md | 6 +----- examples/09_Kotlin_JS/05_Canvas.md | 6 +----- examples/09_Kotlin_JS/06_HtmlBuilder.md | 6 +----- 5 files changed, 6 insertions(+), 29 deletions(-) diff --git a/examples/09_Kotlin_JS/01_dynamic.md b/examples/09_Kotlin_JS/01_dynamic.md index 47c6677..d84bc8a 100755 --- a/examples/09_Kotlin_JS/01_dynamic.md +++ b/examples/09_Kotlin_JS/01_dynamic.md @@ -4,9 +4,7 @@ That is needed in order to interoperate with untyped or loosely typed environments, such as the JavaScript ecosystem. -
- -```kotlin +```run-kotlin-js fun main(){ //sampleStart val a: dynamic = "abc" // 1 @@ -28,8 +26,6 @@ fun main(){ } ``` -
- 1. Any value can be assigned to a `dynamic` variable type. 2. A dynamic value can be assigned to anything. 3. A dynamic variable can be passed as an argument to any function. diff --git a/examples/09_Kotlin_JS/02_js_function.md b/examples/09_Kotlin_JS/02_js_function.md index 678b9d7..cf7768e 100755 --- a/examples/09_Kotlin_JS/02_js_function.md +++ b/examples/09_Kotlin_JS/02_js_function.md @@ -4,22 +4,17 @@ You can inline JavaScript code into your Kotlin code using the js("…") functio This should be used with extreme care. -
- -```kotlin +```run-kotlin-js fun main() { // sampleStart js("alert(\"alert from Kotlin!\")") // 1 // sampleEnd } ``` -
1. Sending a JavaScript alert from a Kotlin function. -
- -```kotlin +```run-kotlin-js fun main(){ //sampleStart val json = js("{}") // 1 @@ -31,8 +26,6 @@ fun main(){ } ``` -
- 1. Creates a JavaScript object literal. The `js(...)` function return type is `dynamic`. 2. Adds some properties by utilizing the `dynamic` type capabilities. 3. Passes the JSON to JavaScript API. diff --git a/examples/09_Kotlin_JS/03_external.md b/examples/09_Kotlin_JS/03_external.md index c0bd256..cee6d84 100755 --- a/examples/09_Kotlin_JS/03_external.md +++ b/examples/09_Kotlin_JS/03_external.md @@ -2,9 +2,7 @@ *external* keyword allows to declare existing JavaScript API in a type-safe way. -
- -```kotlin +```run-kotlin-js external fun alert(msg: String) // 1 fun main() { @@ -12,8 +10,6 @@ fun main() { } ``` -
- 1. Declares an existing JavaScript function `alert` which takes a single `String` argument. 2. Uses `alert` as if it were regular Kotlin. diff --git a/examples/09_Kotlin_JS/05_Canvas.md b/examples/09_Kotlin_JS/05_Canvas.md index 7a369e2..3a32baf 100755 --- a/examples/09_Kotlin_JS/05_Canvas.md +++ b/examples/09_Kotlin_JS/05_Canvas.md @@ -4,9 +4,7 @@ The following example demonstrates usage of HTML5 Canvas from Kotlin. Here strange creatures are watching the kotlin logo. You can drag'n'drop them as well as the logo. Doubleclick to add more creatures but be careful. They may be watching you! -
- -```kotlin +```run-kotlin-js package creatures import jquery.* @@ -354,5 +352,3 @@ fun main(args: Array) { } ``` -
- diff --git a/examples/09_Kotlin_JS/06_HtmlBuilder.md b/examples/09_Kotlin_JS/06_HtmlBuilder.md index 4c80cd5..05f7591 100755 --- a/examples/09_Kotlin_JS/06_HtmlBuilder.md +++ b/examples/09_Kotlin_JS/06_HtmlBuilder.md @@ -4,9 +4,7 @@ Kotlin provides you with an option to describe structured data in a declarative Below is an example of a type-safe Groovy-style builder. In this example, we will describe an HTML page in Kotlin. -
- -```kotlin +```run-kotlin-js package html import org.w3c.dom.* @@ -117,8 +115,6 @@ fun html(init: HTML.() -> Unit): HTML { ``` -
- 1. `html` is actually a function call that takes a [lambda expression](http://kotlinlang.org/docs/reference/lambdas.html) as an argument. `html` function takes one parameter which is itself a function. The type of the function is `HTML.() -> Unit`, which is a function type with receiver. From 9105b168181a5dd3ce5265faa8b90e8183c73264 Mon Sep 17 00:00:00 2001 From: Prendota Date: Mon, 3 Jun 2019 16:05:04 +0300 Subject: [PATCH 09/95] chore: migrate into to new syntax --- examples/01_introduction/01_Hello world.md | 11 ++--------- examples/01_introduction/02_Functions.md | 6 +----- 2 files changed, 3 insertions(+), 14 deletions(-) diff --git a/examples/01_introduction/01_Hello world.md b/examples/01_introduction/01_Hello world.md index 6398972..a0795bc 100755 --- a/examples/01_introduction/01_Hello world.md +++ b/examples/01_introduction/01_Hello world.md @@ -1,8 +1,6 @@ # Hello World -
- -```kotlin +```run-kotlin package org.kotlinlang.play // 1 fun main() { // 2 @@ -10,20 +8,15 @@ fun main() { // 2 } ``` -
- 1. Kotlin code is usually defined in packages. Package specification is optional: If you don't specify a package in a source file, its content goes to the default package. 2. An entry point to a Kotlin application is the `main` function. In Kotlin 1.3, you can declare `main` without any parameters. The return type is not specified, which means that the function returns nothing. 3. `println` writes a line to the standard output. It is imported implicitly. Also note that semicolons are optional. In Kotlin versions earlier than 1.3, the `main` function must have a parameter of type `Array`. -
- -```kotlin +```run-kotlin fun main(args: Array) { println("Hello, World!") } ``` -
diff --git a/examples/01_introduction/02_Functions.md b/examples/01_introduction/02_Functions.md index 59858ac..40cbf3f 100755 --- a/examples/01_introduction/02_Functions.md +++ b/examples/01_introduction/02_Functions.md @@ -2,9 +2,7 @@ ### Default Parameter Values and Named Arguments -
- -```kotlin +```run-kotlin fun printMessage(message: String): Unit { // 1 println(message) } @@ -28,8 +26,6 @@ fun main() { } ``` -
- 1. A simple function that takes a parameter of type `String` and returns `Unit` (i.e., no return value). 2. A function that takes a second [optional parameter with default value](https://kotlinlang.org/docs/reference/functions.html#default-arguments) `Info`. The return type is omitted, meaning that it's actually `Unit`. 3. A function that returns an integer. From 7c60005050fb4acc0e2eab8d43c3bb6a9c71b5fe Mon Sep 17 00:00:00 2001 From: Prendota Date: Mon, 3 Jun 2019 16:05:38 +0300 Subject: [PATCH 10/95] docs(null-safe): migrate into to new syntax --- examples/01_introduction/04_Null Safety.md | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/examples/01_introduction/04_Null Safety.md b/examples/01_introduction/04_Null Safety.md index aaa44da..d8d0aae 100755 --- a/examples/01_introduction/04_Null Safety.md +++ b/examples/01_introduction/04_Null Safety.md @@ -2,9 +2,7 @@ In an effort to rid the world of `NullPointerException`, variable types in Kotlin don't allow the assignment of `null`. If you need a variable that can be null, declare it nullable by adding `?` at the end of its type. -
- -```kotlin +```run-kotlin fun main() { //sampleStart var neverNull: String = "This can't be null" // 1 @@ -29,8 +27,6 @@ fun main() { } ``` -
- 1. Declares a non-`null` String variable. 2. When trying to assign `null` to non-nullable variable, a compilation error is produced. 3. Declares a nullable String variable. @@ -46,9 +42,7 @@ fun main() { Sometimes Kotlin programs need to work with null values, such as when interacting with external Java code or representing a truly absent state. Kotlin provides null tracking to elegantly deal with such situations. -
- -```kotlin +```run-kotlin //sampleStart fun describeString(maybeString: String?): String { // 1 if (maybeString != null && maybeString.length > 0) { // 2 @@ -64,8 +58,6 @@ fun main() { } ``` -
- 1. A function that takes in a nullable string and returns its description. 2. If the given string is not `null` and not empty, return information about its length. 3. Otherwise, tell the caller that the string is empty or null. From 7d843fb11f2bbea7f1ec1b5706b673a9634b3baa Mon Sep 17 00:00:00 2001 From: Prendota Date: Mon, 3 Jun 2019 16:07:11 +0300 Subject: [PATCH 11/95] docs(classes): migrate into to new syntax --- examples/01_introduction/05_Classes.md | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/examples/01_introduction/05_Classes.md b/examples/01_introduction/05_Classes.md index 2b17c04..b206ed6 100755 --- a/examples/01_introduction/05_Classes.md +++ b/examples/01_introduction/05_Classes.md @@ -3,10 +3,8 @@ The [class declaration](https://kotlinlang.org/docs/reference/classes.html#classes) consists of the class name, the class header (specifying its type parameters, the primary constructor etc.) and the class body, surrounded by curly braces. Both the header and the body are optional; if the class has no body, curly braces can be omitted. - -
-```kotlin +```run-kotlin class Customer // 1 class Contact(val id: Int, var email: String) // 2 @@ -22,8 +20,6 @@ fun main() { } ``` -
- 1. Declares a class named `Customer` without any properties or user-defined constructors. A non-parameterized default constructor is created by Kotlin automatically. 2. Declares a class with two properties: immutable `id` and mutable `email`, and a constructor with two parameters `id` and `email`. 3. Creates an instance of the class `Customer` via the default constructor. Note that there is no `new` keyword in Kotlin. From 63fcf0e7ac92c49c076142adce8e96a087dcfa54 Mon Sep 17 00:00:00 2001 From: Prendota Date: Mon, 3 Jun 2019 16:07:50 +0300 Subject: [PATCH 12/95] docs: migrate generics to new syntax --- examples/01_introduction/06_Generics.md | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/examples/01_introduction/06_Generics.md b/examples/01_introduction/06_Generics.md index ef5290d..52697b5 100755 --- a/examples/01_introduction/06_Generics.md +++ b/examples/01_introduction/06_Generics.md @@ -6,9 +6,7 @@ The first way to use generics in Kotlin is creating generic classes. -
- -```kotlin +```run-kotlin //sampleStart class MutableStack(vararg items: E) { // 1 @@ -44,7 +42,6 @@ fun main() { ``` -
1. Defines a generic class `MutableStack` where `E` is called the _generic type parameter_. At use-site, it is assigned to a specific type such as `Int` by declaring a `MutableStack`. 2. Inside the generic class, `E` can be used as a parameter like any other type. @@ -57,9 +54,8 @@ Note that the implementation makes heavy use of Kotlin's shorthand syntax for fu You can also [generify functions](https://kotlinlang.org/docs/reference/generics.html#generic-functions) if their logic is independent of a specific type. For instance, you can write a utility function to create mutable stacks: -
-```kotlin +```run-kotlin class MutableStack(vararg items: E) { // 1 private val elements = items.toMutableList() @@ -87,6 +83,4 @@ fun main() { //sampleEnd ``` -
- Note that the compiler can infer the generic type from the parameters of `mutableStackOf` so that you don't have to write `mutableStackOf(...)`. From 8401e4d08ee0e28d863484d97048d6021724c80b Mon Sep 17 00:00:00 2001 From: Prendota Date: Mon, 3 Jun 2019 16:08:29 +0300 Subject: [PATCH 13/95] docs: migrate Inheritance to new syntax --- examples/01_introduction/07_Inheritance.md | 18 +++--------------- 1 file changed, 3 insertions(+), 15 deletions(-) diff --git a/examples/01_introduction/07_Inheritance.md b/examples/01_introduction/07_Inheritance.md index 50805c5..4d7f277 100755 --- a/examples/01_introduction/07_Inheritance.md +++ b/examples/01_introduction/07_Inheritance.md @@ -2,9 +2,7 @@ Kotlin fully supports the traditional object-oriented inheritance mechanism. -
- -```kotlin +```run-kotlin open class Dog { // 1 open fun sayHello() { // 2 println("wow wow!") @@ -23,8 +21,6 @@ fun main() { } ``` -
- 1. Kotlin classes are _final_ by default. If you want to allow the class inheritance, mark the class with the `open` modifier. 2. Kotlin methods are also _final_ by default. As with the classes, the `open` modifier allows overriding them. 3. A class inherits a superclass when you specify the `: SuperclassName()` after its name. The empty parentheses `()` indicate an invocation of the superclass default constructor. @@ -32,9 +28,7 @@ fun main() { ### Inheritance with Parameterized Constructor -
- -```kotlin +```run-otlin //sampleStart open class Tiger(val origin: String) { fun sayHello() { @@ -51,16 +45,13 @@ fun main() { //sampleEnd ``` -
1. If you want to use a parameterized constructor of the superclass when creating a subclass, provide the constructor arguments in the subclass declaration. ### Passing Constructor Arguments to Superclass -
- -```kotlin +```run-kotlin //sampleStart open class Lion(val name: String, val origin: String) { fun sayHello() { @@ -77,9 +68,6 @@ fun main() { //sampleEnd ``` -
- - 1. `name` in the `Asiatic` declaration is neither a `var` nor `val`: it's a constructor argument, whose value is passed to the `name` property of the superclass `Lion`. 2. Creates an `Asiatic` instance with the name `Rufo`. The call invokes the `Lion` constructor with arguments `Rufo` and `India`. From dca8c307dc88d02a835219cd1aa511c65e6ca9eb Mon Sep 17 00:00:00 2001 From: Prendota Date: Mon, 3 Jun 2019 16:10:15 +0300 Subject: [PATCH 14/95] docs: migrate when to new syntax --- examples/02_control_flow/01_When.md | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/examples/02_control_flow/01_When.md b/examples/02_control_flow/01_When.md index 157f0a7..34f55cd 100755 --- a/examples/02_control_flow/01_When.md +++ b/examples/02_control_flow/01_When.md @@ -4,9 +4,7 @@ Instead of the widely used `switch` statement, Kotlin provides the more flexible ## When Statement -
- -```kotlin +```run-kotlin fun main() { cases("Hello") cases(1) @@ -28,8 +26,6 @@ fun cases(obj: Any) { // 1 class MyClass ``` -
- 1. This is a `when` statement. 2. Checks whether `obj` equals to one. 3. Checks whether `obj` equals to `Hello`. @@ -41,9 +37,7 @@ Note that all branch conditions are checked sequentially until one of them is sa ## When Expression -
- -```kotlin +```run-kotlin fun main() { println(whenAssign("Hello")) println(whenAssign(3.4)) @@ -64,7 +58,6 @@ fun whenAssign(obj: Any): Any { class MyClass ``` -
1. This is a `when` expression. 2. Sets the value to `"one"` if `obj` equals to one. From 7ec79c4f38be1ad378fdf9094d1f0a477b22faff Mon Sep 17 00:00:00 2001 From: Prendota Date: Mon, 3 Jun 2019 16:11:13 +0300 Subject: [PATCH 15/95] docs: migrate loops to new syntax --- examples/02_control_flow/02_Loops.md | 18 +++--------------- 1 file changed, 3 insertions(+), 15 deletions(-) diff --git a/examples/02_control_flow/02_Loops.md b/examples/02_control_flow/02_Loops.md index cc57c06..0929d1a 100755 --- a/examples/02_control_flow/02_Loops.md +++ b/examples/02_control_flow/02_Loops.md @@ -6,9 +6,7 @@ Kotlin supports all the commonly used loops: `for`, `while`, `do-while` `for` in Kotlin works the same way as in most languages. -
- -```kotlin +```run-kotlin fun main(args: Array) { //sampleStart val cakes = listOf("carrot", "cheese", "chocolate") @@ -21,17 +19,13 @@ fun main(args: Array) { } ``` -
- 1. Loops through each cake in the list. ### `while` and `do-while` `while` and `do-while` constructs work similarly to most languages as well. -
- -```kotlin +```run-kotlin fun eatACake() = println("Eat a Cake") fun bakeACake() = println("Bake a Cake") @@ -52,8 +46,6 @@ fun main(args: Array) { } ``` -
- 1. Executes the block while the condition is true. 2. Executes the block first and then checking the condition. @@ -61,9 +53,7 @@ fun main(args: Array) { You can define your own iterators in your classes by implementing the `iterator` operator in them. -
- -```kotlin +```run-kotlin class Animal(val name: String) class Zoo(val animals: List) { @@ -84,8 +74,6 @@ fun main() { } ``` -
- 1. Defines an iterator in a class. It must be named `iterator` and have the `operator` modifier. 2. Returns the iterator that meets the following method requirements: * `next()`: `Animal` From 70eec410cdcad2c8b4870c29986f4b9ab7eab045 Mon Sep 17 00:00:00 2001 From: Prendota Date: Mon, 3 Jun 2019 16:11:59 +0300 Subject: [PATCH 16/95] docs: migrate ranges to new syntax --- examples/02_control_flow/03_Ranges.md | 18 +++--------------- 1 file changed, 3 insertions(+), 15 deletions(-) diff --git a/examples/02_control_flow/03_Ranges.md b/examples/02_control_flow/03_Ranges.md index 36df5d7..27bd211 100755 --- a/examples/02_control_flow/03_Ranges.md +++ b/examples/02_control_flow/03_Ranges.md @@ -2,9 +2,7 @@ There is a set of tools for defining ranges in Kotlin. Let's have a brief look at them. -
- -```kotlin +```run-kotlin fun main() { //sampleStart for(i in 0..3) { // 1 @@ -26,17 +24,13 @@ fun main() { } ``` -
- 1. Iterates over a range starting from 0 up to 3 (inclusive). 2. Iterates over a range with a custom increment step for consecutive elements. 5. Iterates over a range in _reverse_ order. Char ranges are also supported: -
- -```kotlin +```run-kotlin fun main() { //sampleStart for (c in 'a'..'d') { // 1 @@ -53,16 +47,12 @@ fun main() { } ``` -
- 1. Iterates over a char range in alphabetical order. 2. Char ranges support `step` and `downTo` as well. Ranges are also useful in `if` statements: -
- -```kotlin +```run-kotlin fun main() { //sampleStart val x = 2 @@ -78,7 +68,5 @@ fun main() { } ``` -
- 1. Checks if a value is in the range. 2. `!in` is the opposite of `in`. From 72f8b6c0cad47d46e8211eb646bede35931e197d Mon Sep 17 00:00:00 2001 From: Prendota Date: Mon, 3 Jun 2019 16:12:17 +0300 Subject: [PATCH 17/95] docs: migrate Equality Checks to new syntax --- examples/02_control_flow/04_Equality Checks.md | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/examples/02_control_flow/04_Equality Checks.md b/examples/02_control_flow/04_Equality Checks.md index 9172153..43165c6 100755 --- a/examples/02_control_flow/04_Equality Checks.md +++ b/examples/02_control_flow/04_Equality Checks.md @@ -4,9 +4,7 @@ Kotlin uses `==` for structural comparison and `===` for referential comparison. More precisely, `a == b` compiles down to `a == null ? b == null : a.equals(b)`. -
- -```kotlin +```run-kotlin fun main(args: Array) { //sampleStart @@ -19,7 +17,5 @@ fun main(args: Array) { } ``` -
- 1. Returns `true` because it calls `authors.equals(writers)` and sets ignore element order. 2. Returns `false` because `authors` and `writers` are distinct references. From 67e0ec80ada5fe5a144830bbc73af515b2197a25 Mon Sep 17 00:00:00 2001 From: Prendota Date: Mon, 3 Jun 2019 16:12:38 +0300 Subject: [PATCH 18/95] docs: migrate Conditional Expression to new syntax --- examples/02_control_flow/05_Conditional expression.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/examples/02_control_flow/05_Conditional expression.md b/examples/02_control_flow/05_Conditional expression.md index f0d19dc..bca0f91 100755 --- a/examples/02_control_flow/05_Conditional expression.md +++ b/examples/02_control_flow/05_Conditional expression.md @@ -2,8 +2,6 @@ There is no ternary operator `condition ? then : else` in Kotlin. Instead, `if` may be used as an expression: -
- ```kotlin fun main() { //sampleStart @@ -14,6 +12,4 @@ fun main() { } ``` -
- 1. `if` is an expression here: it returns a value. From c7d8df4be74a8e52d2bdd89fed7b52a49409a5e3 Mon Sep 17 00:00:00 2001 From: Prendota Date: Mon, 3 Jun 2019 16:15:54 +0300 Subject: [PATCH 19/95] docs: migrate named arg to new syntax --- examples/08_productivity_boosters/01_namedArguments.md | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/examples/08_productivity_boosters/01_namedArguments.md b/examples/08_productivity_boosters/01_namedArguments.md index 65de69a..c6623b1 100755 --- a/examples/08_productivity_boosters/01_namedArguments.md +++ b/examples/08_productivity_boosters/01_namedArguments.md @@ -3,9 +3,7 @@ As with most other programming languages (Java, C++, etc.), Kotlin supports passing arguments to methods and constructors according to the order they are defined. Kotlin also supports [named arguments](https://kotlinlang.org/docs/reference/functions.html#named-arguments) to allow clearer invocations and avoid mistakes with the order of arguments. Such mistakes are hard to find because they are not detected by the compiler, for example, when two sequential arguments have the same type. -
- -```kotlin +```run-kotlin fun format(userName: String, domain: String) = "$userName@$domain" fun main() { @@ -18,8 +16,6 @@ fun main() { } ``` -
- 1. Calls a function with argument values. 2. Calls a function with switched arguments. No syntax errors, but the result _domain.com@username_ is incorrect. 3. Calls a function with named arguments. From 43363d5cc96b85172e7ee2c214eedb81d36e8840 Mon Sep 17 00:00:00 2001 From: Prendota Date: Mon, 3 Jun 2019 16:16:15 +0300 Subject: [PATCH 20/95] docs: migrate str templates to new syntax --- examples/08_productivity_boosters/02_String Templates.md | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/examples/08_productivity_boosters/02_String Templates.md b/examples/08_productivity_boosters/02_String Templates.md index 847cb67..a2f85cf 100755 --- a/examples/08_productivity_boosters/02_String Templates.md +++ b/examples/08_productivity_boosters/02_String Templates.md @@ -2,9 +2,7 @@ [String templates](https://kotlinlang.org/docs/reference/basic-types.html#string-templates) allow you to include variable references and expressions into strings. When the value of a string is requested (for example, by `println`), all references and expressions are substituted with actual values. -
- -```kotlin +```run-kotlin fun main() { //sampleStart val greeting = "Kotliner" @@ -15,8 +13,6 @@ fun main() { } ``` -
- 1. Prints a string with a variable reference. References in strings start with `$`. 2. Prints a string with an expression. Expressions start with `$` and are enclosed in curly braces. From 8c9ac60b686f322607cf9ef62231115d7b1d3156 Mon Sep 17 00:00:00 2001 From: Prendota Date: Mon, 3 Jun 2019 16:17:25 +0300 Subject: [PATCH 21/95] docs: migrate Destructuring Declarations to new syntax --- .../03_Destructuring Declarations.md | 18 +++--------------- 1 file changed, 3 insertions(+), 15 deletions(-) diff --git a/examples/08_productivity_boosters/03_Destructuring Declarations.md b/examples/08_productivity_boosters/03_Destructuring Declarations.md index e1f1fc7..10308de 100755 --- a/examples/08_productivity_boosters/03_Destructuring Declarations.md +++ b/examples/08_productivity_boosters/03_Destructuring Declarations.md @@ -2,9 +2,7 @@ [Destructuring declaration](https://kotlinlang.org/docs/reference/multi-declarations.html#destructuring-declarations) syntax can be very handy, especially when you need an instance only for accessing its members. It lets you define the instance without a specific name therefore saving a few lines of code. -
- -```kotlin +```run-kotlin fun findMinMax(list: List): Pair { // do the math return Pair(50, 100) @@ -25,15 +23,11 @@ fun main() { } ``` -
- 1. Destructures an `Array`. The number of variables on the left side matches the number of arguments on the right side. 2. Maps can be destructured as well. `name` and `age` variables are mapped to the map key and value. 3. Built-in `Pair` and `Triple` types support destructuring too, even as return values from functions. -
- -```kotlin +```run-kotlin data class User(val username: String, val email: String) // 1 fun getUser() = User("Mary", "mary@somewhere.com") @@ -48,16 +42,12 @@ fun main() { } ``` -
- 1. Defines a data class. 2. Destructures an instance. Declared values are mapped to the instance fields. 3. Data class automatically defines the `component1()` and `component2()` methods that will be called during destructuring. 4. Use _underscore_ if you don't need one of the values, avoiding the compiler hint indicating an unused variable. -
- -```kotlin +```run-kotlin class Pair(val first: K, val second: V) { // 1 operator fun component1(): K { return first @@ -75,7 +65,5 @@ fun main() { } ``` -
- 1. Defines a custom `Pair` class with `component1()` and `component2()` methods. 2. Destructures an instance of this class the same way as for built-in `Pair`. From 66f26f80b935d449a22b3f609e71d6e261b2bdf3 Mon Sep 17 00:00:00 2001 From: Prendota Date: Mon, 3 Jun 2019 16:17:42 +0300 Subject: [PATCH 22/95] docs: migrate Smart Casts to new syntax --- examples/08_productivity_boosters/04_Smart Casts.md | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/examples/08_productivity_boosters/04_Smart Casts.md b/examples/08_productivity_boosters/04_Smart Casts.md index c2d488f..a7e0b82 100755 --- a/examples/08_productivity_boosters/04_Smart Casts.md +++ b/examples/08_productivity_boosters/04_Smart Casts.md @@ -5,9 +5,7 @@ The Kotlin compiler is smart enough to perform type casts automatically in most 1. Casts from nullable types to their non-nullable counterparts. 2. Casts from a supertype to a subtype. -
- -```kotlin +```run-kotlin import java.time.LocalDate import java.time.chrono.ChronoLocalDate @@ -36,8 +34,6 @@ fun main() { ``` -
- 1. Declares a nullable variable. 2. Smart-cast to non-nullable (thus allowing direct access to `isLeapYear`). 3. Smart-cast inside a condition (this is possible because, like Java, Kotlin uses [short-circuiting](https://en.wikipedia.org/wiki/Short-circuit_evaluation)). From 232fe8b2217b9a23e84d2b9074e4cc5a13f30ef5 Mon Sep 17 00:00:00 2001 From: Ivan Vinnikov Date: Mon, 3 Jun 2019 17:02:32 +0300 Subject: [PATCH 23/95] docs: migrate to new snippet format. (#85) Migrate examples from old snippet format (
```kotlin...```
) to a new one (
```run-kotlin...```
). --- README.md | 4 +--- examples/01_introduction/02_Functions.md | 18 +++----------- examples/01_introduction/03_Variables.md | 18 +++----------- .../03_special_classes/01_Data classes.md | 6 +---- examples/03_special_classes/02_Enum.md | 12 ++-------- .../03_special_classes/03_Sealed Classes.md | 7 +----- examples/03_special_classes/04_Object.md | 24 ++++--------------- .../01_Higher-Order Functions.md | 12 ++-------- examples/04_functional/02_Lambdas.md | 6 +---- .../04_functional/03_extensionFunctions.md | 12 ++-------- examples/05_Collections/01_List.md | 7 +----- examples/05_Collections/02_Set.md | 6 +---- examples/05_Collections/03_Map.md | 6 +---- examples/05_Collections/04_filter.md | 6 +---- examples/05_Collections/04_map.md | 6 +---- examples/05_Collections/05_existential.md | 18 +++----------- examples/05_Collections/06_find.md | 6 +---- examples/05_Collections/07_firstlast.md | 12 ++-------- examples/05_Collections/08_count.md | 6 +---- examples/05_Collections/10_associateBy.md | 6 +---- examples/05_Collections/11_partition.md | 6 +---- examples/05_Collections/12_flatMap.md | 6 +---- examples/05_Collections/13_max.md | 6 +---- examples/05_Collections/14_sorted.md | 6 +---- examples/05_Collections/15_Map_getValue.md | 6 +---- examples/05_Collections/16_zip.md | 6 +---- examples/05_Collections/17_getOrElse.md | 13 ++-------- examples/06_scope_functions/01_let.md | 6 +---- examples/06_scope_functions/02_run.md | 9 ++----- examples/06_scope_functions/03_with.md | 6 +---- examples/06_scope_functions/04_apply.md | 6 +---- examples/06_scope_functions/05_also.md | 6 +---- .../07_Delegation/01_delegationPattern.md | 6 +---- .../07_Delegation/02_DelegatedProperties.md | 18 +++----------- 34 files changed, 51 insertions(+), 253 deletions(-) diff --git a/README.md b/README.md index 5131e76..2f4facf 100755 --- a/README.md +++ b/README.md @@ -11,13 +11,11 @@ Create markdown file in `examples` folder. Lorem ipsum dolor sit `amet`, consectetur adipisicing elit. Aspernatur, molestias, velit? -
-`​`​`kotlin +`​`​`run-kotlin fun main(args: Array) { println("Hello from template") } `​`​` -
1. Epsum `factorial` non deposit quid pro quo hic escorol. 2. Souvlaki ignitus carborundum e pluribus unum. diff --git a/examples/01_introduction/02_Functions.md b/examples/01_introduction/02_Functions.md index 40cbf3f..c74b18f 100755 --- a/examples/01_introduction/02_Functions.md +++ b/examples/01_introduction/02_Functions.md @@ -40,9 +40,7 @@ fun main() { Member functions and extensions with a single parameter can be turned into [infix functions](https://kotlinlang.org/docs/reference/functions.html#infix-notation). -
- -```kotlin +```run-kotlin fun main() { infix fun Int.times(str: String) = str.repeat(this) // 1 @@ -66,8 +64,6 @@ class Person(val name: String) { } ``` -
- 1. Defines an infix extension function on `Int`. 2. Calls the infix function. 3. Creates a `Pair` by calling the infix function `to` from the standard library. @@ -81,9 +77,7 @@ Note that the example uses [local functions](https://kotlinlang.org/docs/referen Certain functions can be "upgraded" to [operators](https://kotlinlang.org/docs/reference/operator-overloading.html), allowing their calls with the corresponding operator symbol. -
- -```kotlin +```run-kotlin fun main() { //sampleStart operator fun Int.times(str: String) = str.repeat(this) // 1 @@ -96,8 +90,6 @@ fun main() { } ``` -
- 1. This takes the infix function from above one step further using the `operator` modifier. 2. The operator symbol for `times()` is `*` so that you can call the function using `2 * "Bye"`. 3. An operator function allows easy range access on strings. @@ -107,9 +99,7 @@ fun main() { [Varargs](https://kotlinlang.org/docs/reference/functions.html#variable-number-of-arguments-varargs) allow you to pass any number of arguments by separating them with commas. -
- -```kotlin +```run-kotlin fun main() { //sampleStart fun printAll(vararg messages: String) { // 1 @@ -132,8 +122,6 @@ fun main() { } ``` -
- 1. The `vararg` modifier turns a parameter into a vararg. 2. This allows calling `printAll` with any number of string arguments. 3. Thanks to named parameters, you can even add another parameter of the same type after the vararg. This wouldn't be allowed in Java because there's no way to pass a value. diff --git a/examples/01_introduction/03_Variables.md b/examples/01_introduction/03_Variables.md index 8c94061..ac2b958 100755 --- a/examples/01_introduction/03_Variables.md +++ b/examples/01_introduction/03_Variables.md @@ -4,9 +4,7 @@ Kotlin has powerful type inference. While you can explicitly declare the type of compiler do the work by inferring it. Kotlin does not enforce immutability, though it is recommended. In essence use *val* over *var*. -
- -```kotlin +```run-kotlin fun main() { //sampleStart var a: String = "initial" // 1 @@ -17,15 +15,11 @@ fun main() { } ``` -
- 1. Declares a mutable variable and initializing it. 2. Declares an immutable variable and initializing it. 3. Declares an immutable variable and initializing it without specifying the type. The compiler infers the type `Int`. -
- -```kotlin +```run-kotlin fun main() { //sampleStart var e: Int // 1 @@ -34,16 +28,12 @@ fun main() { } ``` -
- 1. Declares a variable without initialization. 2. An attempt to use the variable causes a compiler error: `Variable 'e' must be initialized`. You're free to choose when you initialize a variable, however, it must be initialized before the first read. - -
-```kotlin +```run-kotlin fun someCondition() = true fun main() { @@ -61,8 +51,6 @@ fun main() { } ``` -
- 1. Declares a variable without initialization. 2. Initializes the variable with different values depending on some condition. 3. Reading the variable is possible because it's already been initialized. diff --git a/examples/03_special_classes/01_Data classes.md b/examples/03_special_classes/01_Data classes.md index fc1afbd..3f9e51e 100755 --- a/examples/03_special_classes/01_Data classes.md +++ b/examples/03_special_classes/01_Data classes.md @@ -2,9 +2,7 @@ [Data classes](https://kotlinlang.org/docs/reference/data-classes.html) make it easy to create classes that are used to store values. Such classes are automatically provided with methods for copying, getting a string representation, and using instances in collections. -
- -```kotlin +```run-kotlin data class User(val name: String, val id: Int) // 1 fun main() { @@ -30,8 +28,6 @@ fun main() { } ``` -
- 1. Defines a data class with the `data` modifier. 2. Method `toString` is auto-generated, which makes `println` output look nice. 3. Auto-generated `equals` considers two instances equal if all their properties are equal. diff --git a/examples/03_special_classes/02_Enum.md b/examples/03_special_classes/02_Enum.md index 79cc8cf..85848e1 100755 --- a/examples/03_special_classes/02_Enum.md +++ b/examples/03_special_classes/02_Enum.md @@ -2,9 +2,7 @@ [Enum classes](https://kotlinlang.org/docs/reference/enum-classes.html) are used to model types that represent a finite set of distinct values, such as directions, states, modes, and so forth. -
- -```kotlin +```run-kotlin enum class State { IDLE, RUNNING, FINISHED // 1 } @@ -21,17 +19,13 @@ fun main() { ``` -
- 1. Defines a simple enum class with three enum instances. The number of instances is always finite and they are all distinct. 2. Accesses an enum instance via the class name. 3. With enums, the compiler can infer if a `when`-expression is exhaustive so that you don't need the `else`-case. Enums may contain properties and methods like other classes, separated from the list of instances by a semicolon. -
- -```kotlin +```run-kotlin enum class Color(val rgb: Int) { // 1 RED(0xFF0000), // 2 @@ -51,8 +45,6 @@ fun main() { ``` -
- 1. Defines an enum class with a property and a method. 2. Each instance must pass an argument for the constructor parameter. 3. Enum class members are separated from the instance definitions by a semicolon. diff --git a/examples/03_special_classes/03_Sealed Classes.md b/examples/03_special_classes/03_Sealed Classes.md index 60927a5..466c829 100755 --- a/examples/03_special_classes/03_Sealed Classes.md +++ b/examples/03_special_classes/03_Sealed Classes.md @@ -2,9 +2,7 @@ [Sealed classes](https://kotlinlang.org/docs/reference/sealed-classes.html) let you restrict the use of inheritance. Once you declare a class sealed, nobody else can create its subclasses. -
- -```kotlin +```run-kotlin sealed class Mammal(val name: String) // 1 class Cat(val catName: String) : Mammal(catName) // 2 @@ -22,9 +20,6 @@ fun main() { } ``` -
- - 1. Defines a sealed class. 2. Defines subclasses. Note that all subclasses must be in the same file. 3. Uses an instance of the sealed class as an argument in a `when` expression. diff --git a/examples/03_special_classes/04_Object.md b/examples/03_special_classes/04_Object.md index 6e14d8e..ac414b6 100755 --- a/examples/03_special_classes/04_Object.md +++ b/examples/03_special_classes/04_Object.md @@ -2,9 +2,7 @@ Classes and objects in Kotlin work the same way as in most object-oriented languages: a *class* is a blueprint, and an *object* is an instance of a class. Usually, you define a class and then create multiple instances of that class: -
- -```kotlin +```run-kotlin import java.util.Random class LuckDispatcher { //1 @@ -23,8 +21,6 @@ fun main() { } ``` -
- 1. Defines a blueprint. 2. Defines a method. 3. Creates instances. @@ -44,9 +40,7 @@ Here is a basic typical usage of an `object` **expression**: a simple object/pro There is no need to do so in class declaration: you create a single object, declare its members and access it within one function. Objects like this are often created in Java as anonymous class instances. -
- -```kotlin +```run-kotlin fun rentPrice(standardDays: Int, festivityDays: Int, specialDays: Int): Unit { //1 val dayRates = object { //2 @@ -66,8 +60,6 @@ fun main() { } ``` -
- 1. Creates a function with parameters. 2. Creates an object to use when calculating the result value. 3. Accesses the object's properties. @@ -78,9 +70,7 @@ fun main() { You can also use the `object` **declaration**. It isn't an expression, and can't be used in a variable assignment. You should use it to directly access its members: -
- -```kotlin +```run-kotlin object DoAuth { //1 fun takeParams(username: String, password: String){ //2 println("input Auth parameters = $username:$password") @@ -93,8 +83,6 @@ fun main(){ ``` -
- 1. Creates an object declaration. 2. Defines the object method. 3. Calls the method. This is when the object is actually created. @@ -105,9 +93,7 @@ An object declaration inside a class defines another useful case: the **companio Syntactically it's similar to the static methods in Java: you call object members using its *class name* as a qualifier. If you plan to use a companion object in Kotlin, consider using a *package-level* function instead. -
- -```kotlin +```run-kotlin class BigBen { //1 companion object Bonger { //2 fun getBongs(nTimes: Int) { //3 @@ -123,8 +109,6 @@ fun main() { } ``` -
- 1. Defines a class. 2. Defines a companion. Its name can be omitted. 3. Defines a companion object method. diff --git a/examples/04_functional/01_Higher-Order Functions.md b/examples/04_functional/01_Higher-Order Functions.md index d9c6488..9107a33 100755 --- a/examples/04_functional/01_Higher-Order Functions.md +++ b/examples/04_functional/01_Higher-Order Functions.md @@ -4,9 +4,7 @@ A [*higher-order function*](https://kotlinlang.org/docs/reference/lambdas.html) ### Taking Functions as Parameters -
- -```kotlin +```run-kotlin fun calculate(x: Int, y: Int, operation: (Int, Int) -> Int): Int { // 1 return operation(x, y) // 2 } @@ -20,8 +18,6 @@ fun main() { } ``` -
- 1. Declares a higher-order function. It takes two integer parameters, `x` and `y`. Additionally, it takes another function `operation` as a parameter. The `operation` parameters and return type are also defined in the declaration. 2. The higher order function returns the result of `operation` invocation with the supplied agruments. 3. Declares a function that matches the `operation`signature. @@ -30,9 +26,7 @@ fun main() { ### Returning Functions -
- -```kotlin +```run-kotlin fun operation(): (Int) -> Int { // 1 return ::square } @@ -45,8 +39,6 @@ fun main() { } ``` -
- 1. Declares a higher-order function that returns a function. 2. Declares a function matching the signature. 3. Invokes `operation` to get the result assigned to a variable. Here `func` becomes `square` which is returned by `operation`. diff --git a/examples/04_functional/02_Lambdas.md b/examples/04_functional/02_Lambdas.md index 2868abb..73c4729 100755 --- a/examples/04_functional/02_Lambdas.md +++ b/examples/04_functional/02_Lambdas.md @@ -2,9 +2,7 @@ [*Lambda functions*](https://kotlinlang.org/docs/reference/lambdas.html) ("lambdas") are a simple way to create functions ad-hoc. Lambdas can be denoted very concisely in many cases thanks to type inference and the implicit `it` variable. -
- -```kotlin +```run-kotlin fun main() { //sampleStart // All examples create a function object that performs upper-casing. @@ -31,8 +29,6 @@ fun main() { } ``` -
- 1. A lambda in all its glory, with explicit types everywhere. The lambda is the part in curly braces, which is assigned to a variable of type `(String) -> String` (a function type). 2. Type inference inside lambda: the type of the lambda parameter is inferred from the type of the variable it's assigned to. 3. Type inference outside lambda: the type of the variable is inferred from the type of the lambda parameter and return value. diff --git a/examples/04_functional/03_extensionFunctions.md b/examples/04_functional/03_extensionFunctions.md index 6602016..ac1658e 100755 --- a/examples/04_functional/03_extensionFunctions.md +++ b/examples/04_functional/03_extensionFunctions.md @@ -2,9 +2,7 @@ Kotlin lets you add new members to any class with the [extensions](https://kotlinlang.org/docs/reference/extensions.html) mechanism. Namely, there are two types of extensions: extension functions and extension properties. They look a lot like normal functions and properties but with one important difference: you need to specify the type that you extend. -
- -```kotlin +```run-kotlin data class Item(val name: String, val price: Float) // 1 data class Order(val items: Collection) @@ -26,8 +24,6 @@ fun main() { } ``` -
- 1. Defines simple models of `Item` and `Order`. `Order` can contain a collection of `Item` objects. 2. Adds extension functions for the `Order` type. 3. Adds an extension property for the `Order` type. @@ -35,10 +31,8 @@ fun main() { 5. Accesses the extension property on an instance of `Order`. It is even possible to execute extensions on `null` references. In an extension function, you can check the object for `null` and use the result in your code: - -
-```kotlin +```run-kotlin //sampleStart fun T?.nullSafeToString() = this?.toString() ?: "NULL" // 1 //sampleEnd @@ -47,5 +41,3 @@ fun main() { println("Kotlin".nullSafeToString()) } ``` - -
diff --git a/examples/05_Collections/01_List.md b/examples/05_Collections/01_List.md index 6119688..f38816b 100644 --- a/examples/05_Collections/01_List.md +++ b/examples/05_Collections/01_List.md @@ -2,9 +2,7 @@ A [list](https://kotlinlang.org/docs/reference/collections.html) is an ordered collection of items. In Kotlin, lists can be either mutable (`MutableList`) or read-only (`List`). For list creation, use the standard library functions `listOf()` for read-only lists and `mutableListOf()` for mutable lists. To prevent unwanted modifications, obtain read-only views of mutable lists by casting them to `List`. -
- -```kotlin +```run-kotlin val systemUsers: MutableList = mutableListOf(1, 2, 3) // 1 val sudoers: List = systemUsers // 2 @@ -26,9 +24,6 @@ fun main() { } ``` -
- - 1. Creates a `MutableList`. 2. Creates a read-only view of the list. 3. Adds a new item to the `MutableList`. diff --git a/examples/05_Collections/02_Set.md b/examples/05_Collections/02_Set.md index 6ab6a6d..7e83c28 100644 --- a/examples/05_Collections/02_Set.md +++ b/examples/05_Collections/02_Set.md @@ -2,9 +2,7 @@ A [set](https://kotlinlang.org/docs/reference/collections.html) is an unordered collection that does not support duplicates. For creating sets, there are functions `setOf()` and `mutableSetOf()`. A read-only view of a mutable set can be obtained by casting it to `Set`. -
- -```kotlin +```run-kotlin val openIssues: MutableSet = mutableSetOf("uniqueDescr1", "uniqueDescr2", "uniqueDescr3") // 1 fun addIssue(uniqueDesc: String): Boolean { @@ -24,8 +22,6 @@ fun main() { } ``` -
- 1. Adds an element to the `Set`. 2. Returns a boolean value showing if the element was actually added. 3. Returns a string, based on function input parameter. diff --git a/examples/05_Collections/03_Map.md b/examples/05_Collections/03_Map.md index 28f8013..c489307 100644 --- a/examples/05_Collections/03_Map.md +++ b/examples/05_Collections/03_Map.md @@ -2,9 +2,7 @@ A [map](https://kotlinlang.org/docs/reference/collections.html) is a collection of key/value pairs, where each key is unique and is used to retrieve the corresponding value. For creating maps, there are functions `mapOf()` and `mutableMapOf()`. A read-only view of a mutable map can be obtained by casting it to `Map`. -
- -```kotlin +```run-kotlin const val POINTS_X_PASS: Int = 15 val EZPassAccounts: MutableMap = mutableMapOf(1 to 100, 2 to 100, 3 to 100) // 1 val EZPassReport: Map = EZPassAccounts // 2 @@ -34,8 +32,6 @@ fun main() { } ``` -
- 1. Creates a mutable `Map`. 2. Creates a read-only view of the `Map`. 3. Checks if the `Map`'s key exists. diff --git a/examples/05_Collections/04_filter.md b/examples/05_Collections/04_filter.md index de7121b..978bf5c 100755 --- a/examples/05_Collections/04_filter.md +++ b/examples/05_Collections/04_filter.md @@ -2,9 +2,7 @@ *filter* function enables you to filter collections. It takes a filter predicate as a lambda-parameter. The predicate is applied to each element. Elements that make the predicate `true` are returned in the result collection. -
- -```kotlin +```run-kotlin fun main() { //sampleStart @@ -21,8 +19,6 @@ fun main() { } ``` -
- 1. Defines collection of numbers. 2. Gets positive numbers. 3. Uses the shorter `it` notation to get negative numbers. diff --git a/examples/05_Collections/04_map.md b/examples/05_Collections/04_map.md index 00d48c2..825bad1 100755 --- a/examples/05_Collections/04_map.md +++ b/examples/05_Collections/04_map.md @@ -2,9 +2,7 @@ *map* extension function enables you to apply a transformation to all elements in a collection. It takes a transformer function as a lambda-parameter. -
- -```kotlin +```run-kotlin fun main() { //sampleStart @@ -21,8 +19,6 @@ fun main() { } ``` -
- 1. Defines a collection of numbers. 2. Doubles numbers. 3. Uses the shorter `it` notation to triple the numbers. diff --git a/examples/05_Collections/05_existential.md b/examples/05_Collections/05_existential.md index 970386a..d685dcc 100755 --- a/examples/05_Collections/05_existential.md +++ b/examples/05_Collections/05_existential.md @@ -6,9 +6,7 @@ These functions check the existence of collection elements that match a given pr Function `any` returns `true` if the collection contains **at least one** element that matches the given predicate. -
- -```kotlin +```run-kotlin fun main() { //sampleStart @@ -25,8 +23,6 @@ fun main() { } ``` -
- 1. Defines a collection of numbers. 2. Checks if there are negative elements. 3. Checks if there are elements greater than `6`. @@ -36,9 +32,7 @@ fun main() { Function `all` returns `true` if **all** elements in collection match the given predicate. -
- -```kotlin +```run-kotlin fun main() { //sampleStart @@ -55,8 +49,6 @@ fun main() { } ``` -
- 1. Defines a collection of numbers. 2. Checks whether all elements are even. 3. Checks whether all elements are less than `6`. @@ -66,9 +58,7 @@ fun main() { Function `none` returns `true` if there are **no** elements that match the given predicate in the collection. -
- -```kotlin +```run-kotlin fun main() { //sampleStart @@ -85,8 +75,6 @@ fun main() { } ``` -
- 1. Defines a collection of numbers. 2. Checks if there are no odd elements (all elements are even). 3. Checks if there are no elements greater than 6. diff --git a/examples/05_Collections/06_find.md b/examples/05_Collections/06_find.md index 154d1be..34ac8d9 100755 --- a/examples/05_Collections/06_find.md +++ b/examples/05_Collections/06_find.md @@ -3,9 +3,7 @@ `find` and `findLast` functions return the first or the last collection element that matches the given predicate. If there are no such elements, functions return `null`. -
- -```kotlin +```run-kotlin fun main() { //sampleStart @@ -23,8 +21,6 @@ fun main() { } ``` -
- 1. Defines a collection of words. 2. Looks for the first word starting with "some". 3. Looks for the last word starting with "some". diff --git a/examples/05_Collections/07_firstlast.md b/examples/05_Collections/07_firstlast.md index a83b1ae..9c9b920 100755 --- a/examples/05_Collections/07_firstlast.md +++ b/examples/05_Collections/07_firstlast.md @@ -6,9 +6,7 @@ These functions return the first and the last element of the collection correspo If a collection is empty or doesn't contain elements matching the predicate, the functions throw `NoSuchElementException`. -
- -```kotlin +```run-kotlin fun main() { //sampleStart @@ -26,8 +24,6 @@ fun main() { } ``` -
- 1. Defines a collection of numbers. 2. Picks the first element. 3. Picks the last element. @@ -38,9 +34,7 @@ fun main() { These functions work almost the same way with one difference: they return `null` if there are no matching elements. -
- -```kotlin +```run-kotlin fun main() { //sampleStart @@ -62,8 +56,6 @@ fun main() { } ``` -
- 1. Defines a collection of words. 2. Defines an empty collection. 3. Picks the first element from empty collection. It supposed to be `null`. diff --git a/examples/05_Collections/08_count.md b/examples/05_Collections/08_count.md index daa6875..ee0792d 100755 --- a/examples/05_Collections/08_count.md +++ b/examples/05_Collections/08_count.md @@ -2,9 +2,7 @@ `count` functions returns either the total number of elements in a collection or the number of elements matching the given predicate. -
- -```kotlin +```run-kotlin fun main() { //sampleStart @@ -19,8 +17,6 @@ fun main() { } ``` -
- 1. Defines a collection of numbers. 2. Counts the total number of elements. 3. Counts the number of even elements. diff --git a/examples/05_Collections/10_associateBy.md b/examples/05_Collections/10_associateBy.md index f723f55..2b6a2ea 100755 --- a/examples/05_Collections/10_associateBy.md +++ b/examples/05_Collections/10_associateBy.md @@ -9,9 +9,7 @@ The difference between `associateBy` and `groupBy` is how they process objects w The returned map preserves the entry iteration order of the original collection. -
- -```kotlin +```run-kotlin fun main() { //sampleStart @@ -37,8 +35,6 @@ fun main() { } ``` -
- 1. Defines a data class that describes a person. 2. Defines a collection of people. 3. Builds a map from phone numbers to their owners' information. `it.phone` is the `keySelector` here. The `valueSelector` is not provided, so the values of the map are `Person` objects themselves. diff --git a/examples/05_Collections/11_partition.md b/examples/05_Collections/11_partition.md index 27db074..df24362 100755 --- a/examples/05_Collections/11_partition.md +++ b/examples/05_Collections/11_partition.md @@ -4,9 +4,7 @@ * Elements for which the predicate is `true`. * Elements for which the predicate is `false`. -
- -```kotlin +```run-kotlin fun main() { //sampleStart @@ -25,8 +23,6 @@ fun main() { ``` -
- 1. Defines a collection of numbers. 2. Splits `numbers` into a `Pair` of lists with even and odd numbers. 3. Splits `numbers` into two lists with positive and negative numbers. Pair destructuring is applied here to get the `Pair` members. diff --git a/examples/05_Collections/12_flatMap.md b/examples/05_Collections/12_flatMap.md index d6cd158..742ef3d 100755 --- a/examples/05_Collections/12_flatMap.md +++ b/examples/05_Collections/12_flatMap.md @@ -2,9 +2,7 @@ `flatMap` transforms each element of a collection into an iterable object and builds a single list of the transformation results. The transformation is user-defined. -
- -```kotlin +```run-kotlin fun main() { //sampleStart @@ -18,7 +16,5 @@ fun main() { } ``` -
- 1. Defines a collection of numbers. 2. Builds a list in which every collection element is repeated three times. Important thing is that it's **not** a list of lists; it's a list of integers with nine elements. diff --git a/examples/05_Collections/13_max.md b/examples/05_Collections/13_max.md index 85dcf08..49768ce 100755 --- a/examples/05_Collections/13_max.md +++ b/examples/05_Collections/13_max.md @@ -2,9 +2,7 @@ `min` and `max` functions return the smallest and the largest element of a collection. If the collection is empty, they return `null`. -
- -```kotlin +```run-kotlin fun main() { //sampleStart @@ -17,7 +15,5 @@ fun main() { } ``` -
- 1. For non-empty collection functions return the smallest and the largest element. 2. For empty collections both functions return `null`. diff --git a/examples/05_Collections/14_sorted.md b/examples/05_Collections/14_sorted.md index 22d6dc7..26d8e3f 100755 --- a/examples/05_Collections/14_sorted.md +++ b/examples/05_Collections/14_sorted.md @@ -4,9 +4,7 @@ `sortedBy` sorts elements according to natural sort order of the values returned by specified selector function. -
- -```kotlin +```run-kotlin fun main() { //sampleStart @@ -21,8 +19,6 @@ fun main() { } ``` -
- 1. Defines a collection of shuffled numbers. 2. Sorts it in the natural order. 2. Sorts it in the inverted natural order by using `-it` as a selector function. diff --git a/examples/05_Collections/15_Map_getValue.md b/examples/05_Collections/15_Map_getValue.md index c7e640e..6f2051e 100644 --- a/examples/05_Collections/15_Map_getValue.md +++ b/examples/05_Collections/15_Map_getValue.md @@ -5,9 +5,7 @@ When applied to a map, `[]` operator returns the value corresponding to the give `getValue` function returns an existing value corresponding to the given key or throws an exception if the key wasn't found. For maps created with `withDefault`, `getValue` returns the default value instead of throwing an exception. -
- -```kotlin +```run-kotlin fun main(args: Array) { //sampleStart @@ -36,8 +34,6 @@ fun main(args: Array) { } ``` -
- 1. Returns 42 because it's the value corresponding to the key `"key"`. 2. Returns `null` because `"key2"` is not in the map. 3. Returns the default value because `"key2"` is absent. For this key it's 4. diff --git a/examples/05_Collections/16_zip.md b/examples/05_Collections/16_zip.md index 3fd1b6f..9a97fbc 100755 --- a/examples/05_Collections/16_zip.md +++ b/examples/05_Collections/16_zip.md @@ -4,9 +4,7 @@ The size of the result collection equals to the minumum size of a source collection. -
- -```kotlin +```run-kotlin fun main() { //sampleStart @@ -22,8 +20,6 @@ fun main() { } ``` -
- 1. Defines two collections. 2. Merges them into a list of pairs. The infix notation is used here. 3. Merges them into a list of String values by the given transformation. diff --git a/examples/05_Collections/17_getOrElse.md b/examples/05_Collections/17_getOrElse.md index ec22078..919bbed 100644 --- a/examples/05_Collections/17_getOrElse.md +++ b/examples/05_Collections/17_getOrElse.md @@ -3,10 +3,7 @@ `getOrElse` provides safe access to elements of a collection. It takes an index and a function that provides the default value in cases when the index is out of bound. - -
- -```kotlin +```run-kotlin fun main() { //sampleStart @@ -17,16 +14,12 @@ fun main() { } ``` -
- 1. Prints the element at the index `1`. 2. Prints `42` because the index `10` is out of bounds. `getOrElse` can also be applied to `Map` to get the value for the given key. -
- -```kotlin +```run-kotlin fun main() { //sampleStart @@ -42,8 +35,6 @@ fun main() { } ``` -
- 1. Prints the default value because the key `"x"` is not in the map. 2. Prints `3`, the value for the key `"x"`. 3. Prints the default value because the value for the key `"x"` is not defined. diff --git a/examples/06_scope_functions/01_let.md b/examples/06_scope_functions/01_let.md index ba5a638..600b0de 100644 --- a/examples/06_scope_functions/01_let.md +++ b/examples/06_scope_functions/01_let.md @@ -3,9 +3,7 @@ The Kotlin standard library function `let` can be used for scoping and null-checks. When called on an object, `let` executes the given block of code and returns the result of its last expression. The object is accessible inside the block by the reference `it`. -
- -```kotlin +```run-kotlin fun customPrint(s: String) { print(s.toUpperCase()) } @@ -34,8 +32,6 @@ fun main() { } ``` -
- 1. Calls the given block on the result on the string "_test_". 2. Calls the function on "_test_" by the `it` reference. 3. `let` returns the value of this expression. diff --git a/examples/06_scope_functions/02_run.md b/examples/06_scope_functions/02_run.md index 227fc06..068eb73 100644 --- a/examples/06_scope_functions/02_run.md +++ b/examples/06_scope_functions/02_run.md @@ -1,11 +1,9 @@ # run Like [`let`](01_let), `run` is another scoping function from the standard library. Basically, it does the same: executes a code block and returns its result. -The difference is that inside `run` the object is accessed by `this`. This is useful when you want to call the object's methods rather than pass it as an argument.
+The difference is that inside `run` the object is accessed by `this`. This is useful when you want to call the object's methods rather than pass it as an argument. -
- -```kotlin +```run-kotlin fun main() { //sampleStart @@ -24,9 +22,6 @@ fun main() { } ``` -
- - 1. Calls the given block on a nullable variable. 2. Inside `run`, the object's members are accessed without its name. 3. `run` returns the `length` of the given `String` if it's not `null`. diff --git a/examples/06_scope_functions/03_with.md b/examples/06_scope_functions/03_with.md index d4e2b0c..3457799 100644 --- a/examples/06_scope_functions/03_with.md +++ b/examples/06_scope_functions/03_with.md @@ -4,9 +4,7 @@ `with` is a non-extension function that can access members of its argument concisely: you can omit the instance name when referring to its members. -
- -```kotlin +```run-kotlin class Configuration(var host: String, var port: Int) fun main() { @@ -22,5 +20,3 @@ fun main() { //sampleEnd } ``` - -
diff --git a/examples/06_scope_functions/04_apply.md b/examples/06_scope_functions/04_apply.md index 500346e..a59f1d0 100644 --- a/examples/06_scope_functions/04_apply.md +++ b/examples/06_scope_functions/04_apply.md @@ -3,9 +3,7 @@ `apply` executes a block of code on an object and returns the object itself. Inside the block, the object is referenced by `this`. This function is handy for initializing objects. -
- -```kotlin +```run-kotlin data class Person(var name: String, var age: Int, var about: String) { constructor() : this("", 0, "") } @@ -23,8 +21,6 @@ fun main() { } ``` -
- 1. Creates a `Person()` instance with default property values. 2. Applies the code block (next 3 lines) to the instance. diff --git a/examples/06_scope_functions/05_also.md b/examples/06_scope_functions/05_also.md index d34e61e..1802b8b 100644 --- a/examples/06_scope_functions/05_also.md +++ b/examples/06_scope_functions/05_also.md @@ -4,9 +4,7 @@ Inside the block, the object is referenced by `it`, so it's easier to pass it as an argument. This function is handy for embedding additional actions, such as logging in call chains. -
- -```kotlin +```run-kotlin data class Person(var name: String, var age: Int, var about: String) { constructor() : this("", 0, "") } @@ -25,8 +23,6 @@ fun main() { } ``` -
- 1. Creates a `Person()` object with the given property values. 2. Applies the given code block to the object. The return value is the object itself. 3. Calls the logging function passing the object as an argument. diff --git a/examples/07_Delegation/01_delegationPattern.md b/examples/07_Delegation/01_delegationPattern.md index 30e0307..6b567d5 100755 --- a/examples/07_Delegation/01_delegationPattern.md +++ b/examples/07_Delegation/01_delegationPattern.md @@ -2,9 +2,7 @@ Kotlin supports easy implementation of the [delegation pattern](https://kotlinlang.org/docs/reference/delegation.html) on the native level without any boilerplate code. -
- -```kotlin +```run-kotlin interface SoundBehavior { // 1 fun makeSound() } @@ -31,8 +29,6 @@ fun main() { } ``` -
- 1. Defines the interface `SoundBehavior` with one method. 2. The classes `ScreamBehavior` and `RockAndRollBehavior` implement the interface and contain their own implementations of the method. diff --git a/examples/07_Delegation/02_DelegatedProperties.md b/examples/07_Delegation/02_DelegatedProperties.md index c8864f5..591c243 100755 --- a/examples/07_Delegation/02_DelegatedProperties.md +++ b/examples/07_Delegation/02_DelegatedProperties.md @@ -3,9 +3,7 @@ Kotlin provides a mechanism of [delegated properties](http://kotlinlang.org/docs/reference/delegated-properties.html) that allows delegating the calls of the property `set` and `get` methods to a certain object. The delegate object in this case should have the method `getValue`. For mutable properties, you'll also need `setValue`. -
- -```kotlin +```run-kotlin import kotlin.reflect.KProperty class Example { @@ -31,8 +29,6 @@ fun main() { } ``` -
- 1. Delegates property `p` of type `String` to the instance of class `Delegate`. The delegate object is defined after the `by` keyword. 2. Delegation methods. The signatures of these methods are always as shown in the example. Implementations may contain any steps you need. For immutable properties only `getValue` is required. @@ -41,9 +37,7 @@ fun main() { The Kotlin standard library contains a bunch of useful delegates, like `lazy`, `observable`, and other. You may use them as is. For example `lazy`is used for lazy initialization. -
- -```kotlin +```run-kotlin class LazySample { init { println("created!") // 1 @@ -62,8 +56,6 @@ fun main() { } ``` -
- 1. Property `lazy` is not initialized on object creation. 2. The first call to `get()` executes the lambda expression passed to `lazy()` as an argument and saves the result. 3. Further calls to `get()` return the saved result. @@ -75,9 +67,7 @@ If you want thread safety, use `blockingLazy()` instead: it guarantees that the Property delegation can be used for storing properties in a map. This is handy for tasks like parsing JSON or doing other "dynamic" stuff. -
- -```kotlin +```run-kotlin class User(val map: Map) { val name: String by map // 1 val age: Int by map // 1 @@ -93,8 +83,6 @@ fun main() { } ``` -
- 1. Delegates take values from the `map` by the string keys - names of properties. You can delegate mutable properties to a map as well. In this case, the map will be modified upon property assignments. Note that you will need `MutableMap` instead of read-only `Map`. From 96e4b23144d4973f3851b9ee447abd601e4af700 Mon Sep 17 00:00:00 2001 From: Pavel Semyonov Date: Wed, 5 Jun 2019 12:49:25 +0700 Subject: [PATCH 24/95] fix: code sample typo --- examples/01_introduction/07_Inheritance.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/01_introduction/07_Inheritance.md b/examples/01_introduction/07_Inheritance.md index 4d7f277..a7c41e2 100755 --- a/examples/01_introduction/07_Inheritance.md +++ b/examples/01_introduction/07_Inheritance.md @@ -28,7 +28,7 @@ fun main() { ### Inheritance with Parameterized Constructor -```run-otlin +```run-kotlin //sampleStart open class Tiger(val origin: String) { fun sayHello() { From 1f71efcf71ad71e973ff47c33cc055c1840598f7 Mon Sep 17 00:00:00 2001 From: Prendota Date: Mon, 10 Jun 2019 11:41:32 +0300 Subject: [PATCH 25/95] chore: set canvas runnable tag --- examples/09_Kotlin_JS/05_Canvas.md | 2 +- examples/09_Kotlin_JS/06_HtmlBuilder.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/09_Kotlin_JS/05_Canvas.md b/examples/09_Kotlin_JS/05_Canvas.md index 3a32baf..a3f8b0f 100755 --- a/examples/09_Kotlin_JS/05_Canvas.md +++ b/examples/09_Kotlin_JS/05_Canvas.md @@ -4,7 +4,7 @@ The following example demonstrates usage of HTML5 Canvas from Kotlin. Here strange creatures are watching the kotlin logo. You can drag'n'drop them as well as the logo. Doubleclick to add more creatures but be careful. They may be watching you! -```run-kotlin-js +```run-kotlin-canvas package creatures import jquery.* diff --git a/examples/09_Kotlin_JS/06_HtmlBuilder.md b/examples/09_Kotlin_JS/06_HtmlBuilder.md index 05f7591..4dc6e79 100755 --- a/examples/09_Kotlin_JS/06_HtmlBuilder.md +++ b/examples/09_Kotlin_JS/06_HtmlBuilder.md @@ -4,7 +4,7 @@ Kotlin provides you with an option to describe structured data in a declarative Below is an example of a type-safe Groovy-style builder. In this example, we will describe an HTML page in Kotlin. -```run-kotlin-js +```run-kotlin-canvas package html import org.w3c.dom.* From 6ffd9dae3256769067a3ea92435f93edbf631dbf Mon Sep 17 00:00:00 2001 From: Pavel Semyonov <42832629+p7nov@users.noreply.github.com> Date: Fri, 12 Jul 2019 17:51:39 +0700 Subject: [PATCH 26/95] fix: generic type in 06_Generics.md --- examples/01_introduction/06_Generics.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/01_introduction/06_Generics.md b/examples/01_introduction/06_Generics.md index 52697b5..ec9a83c 100755 --- a/examples/01_introduction/06_Generics.md +++ b/examples/01_introduction/06_Generics.md @@ -83,4 +83,4 @@ fun main() { //sampleEnd ``` -Note that the compiler can infer the generic type from the parameters of `mutableStackOf` so that you don't have to write `mutableStackOf(...)`. +Note that the compiler can infer the generic type from the parameters of `mutableStackOf` so that you don't have to write `mutableStackOf(...)`. From 2ed88b51a1e287a246e8868f6f19f0cc766a3fe4 Mon Sep 17 00:00:00 2001 From: nm176 Date: Tue, 16 Jul 2019 19:26:36 -0700 Subject: [PATCH 27/95] fix: typo in 02_Enum.md (#88) --- examples/03_special_classes/02_Enum.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/03_special_classes/02_Enum.md b/examples/03_special_classes/02_Enum.md index 85848e1..3827c6f 100755 --- a/examples/03_special_classes/02_Enum.md +++ b/examples/03_special_classes/02_Enum.md @@ -49,5 +49,5 @@ fun main() { 2. Each instance must pass an argument for the constructor parameter. 3. Enum class members are separated from the instance definitions by a semicolon. 4. The default `toString` returns the name of the instance, here `"RED"`. -5. Calls a method on a enum instance. +5. Calls a method on an enum instance. 6. Calls a method via enum class name. From b4fc3d6f0d149ad079a2cbccd4b312183b055082 Mon Sep 17 00:00:00 2001 From: Jaap Date: Thu, 18 Jul 2019 12:48:45 +0200 Subject: [PATCH 28/95] fix: typo in 16_zip.md (#89) --- examples/05_Collections/16_zip.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/05_Collections/16_zip.md b/examples/05_Collections/16_zip.md index 9a97fbc..9c9901d 100755 --- a/examples/05_Collections/16_zip.md +++ b/examples/05_Collections/16_zip.md @@ -2,7 +2,7 @@ `zip` function merges two given collections into a new collection. By default, the result collection contains `Pairs` of source collection elements with the same index. However, you can define own structure of the result collection element. -The size of the result collection equals to the minumum size of a source collection. +The size of the result collection equals to the minimum size of a source collection. ```run-kotlin fun main() { From 0f5302c2a0e99e0bddaf4eec056f61966a01f517 Mon Sep 17 00:00:00 2001 From: Mike Rinehart <32079048+mrinehart-r7@users.noreply.github.com> Date: Tue, 27 Aug 2019 00:17:26 -0500 Subject: [PATCH 29/95] fix: space in heading in 02_Loops.md (#90) --- examples/02_control_flow/02_Loops.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/02_control_flow/02_Loops.md b/examples/02_control_flow/02_Loops.md index 0929d1a..6194f1c 100755 --- a/examples/02_control_flow/02_Loops.md +++ b/examples/02_control_flow/02_Loops.md @@ -1,4 +1,4 @@ -#Loops +# Loops Kotlin supports all the commonly used loops: `for`, `while`, `do-while` From 9dffc1dd80d92b43bc3a5f0dd2bab7aee02d0982 Mon Sep 17 00:00:00 2001 From: Hamza Lee Date: Fri, 27 Sep 2019 07:02:03 +0100 Subject: [PATCH 30/95] docs: fix typo --- examples/07_Delegation/01_delegationPattern.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/07_Delegation/01_delegationPattern.md b/examples/07_Delegation/01_delegationPattern.md index 6b567d5..5d6bdc3 100755 --- a/examples/07_Delegation/01_delegationPattern.md +++ b/examples/07_Delegation/01_delegationPattern.md @@ -22,7 +22,7 @@ class TomAraya(n:String): SoundBehavior by ScreamBehavior(n) class ElvisPresley(n:String): SoundBehavior by RockAndRollBehavior(n) // 3 fun main() { - val tomAraya = TomAraya("Trash Metal") + val tomAraya = TomAraya("Thrash Metal") tomAraya.makeSound() // 4 val elvisPresley = ElvisPresley("Dancin' to the Jailhouse Rock.") elvisPresley.makeSound() From e61573576eec440ff9ba9e4b72df3498c41d27bd Mon Sep 17 00:00:00 2001 From: Abhilash Mandaliya Date: Fri, 27 Dec 2019 14:59:40 +0530 Subject: [PATCH 31/95] fix: typo correction delegated-properties(#97) For the statement: If you want thread safety, use blockingLazy(), it shows f you want thread safety, use blockingLazy() on the actual page --- examples/07_Delegation/02_DelegatedProperties.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/07_Delegation/02_DelegatedProperties.md b/examples/07_Delegation/02_DelegatedProperties.md index 591c243..91fb7e9 100755 --- a/examples/07_Delegation/02_DelegatedProperties.md +++ b/examples/07_Delegation/02_DelegatedProperties.md @@ -60,7 +60,7 @@ fun main() { 2. The first call to `get()` executes the lambda expression passed to `lazy()` as an argument and saves the result. 3. Further calls to `get()` return the saved result. -If you want thread safety, use `blockingLazy()` instead: it guarantees that the values will be computed only in one thread and that all threads will see the same value. + If you want thread safety, use `blockingLazy()` instead: it guarantees that the values will be computed only in one thread and that all threads will see the same value. ### Storing Properties in a Map From 9db8a73e400dae55df7de2f9bf255f0f92aa8625 Mon Sep 17 00:00:00 2001 From: Arseniy <41956571+arsus11@users.noreply.github.com> Date: Fri, 27 Dec 2019 11:30:59 +0200 Subject: [PATCH 32/95] fix: add space in 01_Data classes.md (#95) Visual change --- examples/03_special_classes/01_Data classes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/03_special_classes/01_Data classes.md b/examples/03_special_classes/01_Data classes.md index 3f9e51e..4b95ae4 100755 --- a/examples/03_special_classes/01_Data classes.md +++ b/examples/03_special_classes/01_Data classes.md @@ -3,7 +3,7 @@ [Data classes](https://kotlinlang.org/docs/reference/data-classes.html) make it easy to create classes that are used to store values. Such classes are automatically provided with methods for copying, getting a string representation, and using instances in collections. ```run-kotlin -data class User(val name: String, val id: Int) // 1 +data class User(val name: String, val id: Int) // 1 fun main() { val user = User("Alex", 1) From 5a1a829c5e1bbad03211658680ae767ca791b3d3 Mon Sep 17 00:00:00 2001 From: Arseniy <41956571+arsus11@users.noreply.github.com> Date: Fri, 27 Dec 2019 11:31:51 +0200 Subject: [PATCH 33/95] fix: add space in 01_delegationPattern.md (#94) Visual change --- examples/07_Delegation/01_delegationPattern.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/07_Delegation/01_delegationPattern.md b/examples/07_Delegation/01_delegationPattern.md index 5d6bdc3..3b8db37 100755 --- a/examples/07_Delegation/01_delegationPattern.md +++ b/examples/07_Delegation/01_delegationPattern.md @@ -23,7 +23,7 @@ class ElvisPresley(n:String): SoundBehavior by RockAndRollBehavior(n) fun main() { val tomAraya = TomAraya("Thrash Metal") - tomAraya.makeSound() // 4 + tomAraya.makeSound() // 4 val elvisPresley = ElvisPresley("Dancin' to the Jailhouse Rock.") elvisPresley.makeSound() } From d6805529a3c7daaadc3042791158a94a0349169c Mon Sep 17 00:00:00 2001 From: Shuying Date: Wed, 1 Jan 2020 20:16:07 +1100 Subject: [PATCH 34/95] Fix run-kotlin for code snippet --- examples/02_control_flow/05_Conditional expression.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/02_control_flow/05_Conditional expression.md b/examples/02_control_flow/05_Conditional expression.md index bca0f91..51cf44b 100755 --- a/examples/02_control_flow/05_Conditional expression.md +++ b/examples/02_control_flow/05_Conditional expression.md @@ -2,7 +2,7 @@ There is no ternary operator `condition ? then : else` in Kotlin. Instead, `if` may be used as an expression: -```kotlin +```run-kotlin fun main() { //sampleStart fun max(a: Int, b: Int) = if (a > b) a else b // 1 From fa848359d82b63227a7a3f42aeb57a79e77f420d Mon Sep 17 00:00:00 2001 From: Joshua Lents Date: Wed, 8 Jan 2020 21:57:11 -0600 Subject: [PATCH 35/95] chore: expand explanation in 03_Sealed Classes.md (#99) Added some more info surrounding the nuance of the sealed keyword. --- examples/03_special_classes/03_Sealed Classes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/03_special_classes/03_Sealed Classes.md b/examples/03_special_classes/03_Sealed Classes.md index 466c829..01a6d6e 100755 --- a/examples/03_special_classes/03_Sealed Classes.md +++ b/examples/03_special_classes/03_Sealed Classes.md @@ -1,6 +1,6 @@ # Sealed Classes -[Sealed classes](https://kotlinlang.org/docs/reference/sealed-classes.html) let you restrict the use of inheritance. Once you declare a class sealed, nobody else can create its subclasses. +[Sealed classes](https://kotlinlang.org/docs/reference/sealed-classes.html) let you restrict the use of inheritance. Once you declare a class sealed, it can only be subclassed from inside the same file where the sealed class is declared. It cannot be subclassed outside of the file where the sealed class is declared. ```run-kotlin sealed class Mammal(val name: String) // 1 From a07e3788e9fd25bfad3f663847d5c8e01bd6ded0 Mon Sep 17 00:00:00 2001 From: Rod Elias Date: Sun, 9 Feb 2020 16:49:02 -0300 Subject: [PATCH 36/95] fix: typo (#100) --- examples/04_functional/01_Higher-Order Functions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/04_functional/01_Higher-Order Functions.md b/examples/04_functional/01_Higher-Order Functions.md index 9107a33..67cee35 100755 --- a/examples/04_functional/01_Higher-Order Functions.md +++ b/examples/04_functional/01_Higher-Order Functions.md @@ -19,7 +19,7 @@ fun main() { ``` 1. Declares a higher-order function. It takes two integer parameters, `x` and `y`. Additionally, it takes another function `operation` as a parameter. The `operation` parameters and return type are also defined in the declaration. -2. The higher order function returns the result of `operation` invocation with the supplied agruments. +2. The higher order function returns the result of `operation` invocation with the supplied arguments. 3. Declares a function that matches the `operation`signature. 4. Invokes the higher-order function passing in two integer values and the function argument `::sum`. `::` is the notation that references a function by name in Kotlin. 5. Invokes the higher-order function passing in a lambda as a function argument. Looks clearer, doesn't it? From ae7fb65d677f41d629bcede04eb267e4d1fa5ff4 Mon Sep 17 00:00:00 2001 From: Rod Elias Date: Mon, 10 Feb 2020 19:46:24 -0300 Subject: [PATCH 37/95] fix: wording --- examples/07_Delegation/02_DelegatedProperties.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/07_Delegation/02_DelegatedProperties.md b/examples/07_Delegation/02_DelegatedProperties.md index 91fb7e9..0c9f584 100755 --- a/examples/07_Delegation/02_DelegatedProperties.md +++ b/examples/07_Delegation/02_DelegatedProperties.md @@ -34,7 +34,7 @@ fun main() { ### Standard Delegates -The Kotlin standard library contains a bunch of useful delegates, like `lazy`, `observable`, and other. You may use them as is. +The Kotlin standard library contains a bunch of useful delegates, like `lazy`, `observable`, and others. You may use them as is. For example `lazy`is used for lazy initialization. ```run-kotlin From 30db85702c79ab2e8389b0813dade9373215d5b3 Mon Sep 17 00:00:00 2001 From: Rod Elias Date: Mon, 10 Feb 2020 23:05:24 -0300 Subject: [PATCH 38/95] fix markers --- examples/09_Kotlin_JS/02_js_function.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/09_Kotlin_JS/02_js_function.md b/examples/09_Kotlin_JS/02_js_function.md index cf7768e..798385b 100755 --- a/examples/09_Kotlin_JS/02_js_function.md +++ b/examples/09_Kotlin_JS/02_js_function.md @@ -6,9 +6,9 @@ This should be used with extreme care. ```run-kotlin-js fun main() { -// sampleStart +//sampleStart js("alert(\"alert from Kotlin!\")") // 1 -// sampleEnd +//sampleEnd } ``` From 44884e514589036290051d600002fba5335df83b Mon Sep 17 00:00:00 2001 From: Pavel Semyonov Date: Thu, 13 Feb 2020 12:08:06 +0700 Subject: [PATCH 39/95] chore: improve range examples --- examples/02_control_flow/03_Ranges.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/02_control_flow/03_Ranges.md b/examples/02_control_flow/03_Ranges.md index 27bd211..276e850 100755 --- a/examples/02_control_flow/03_Ranges.md +++ b/examples/02_control_flow/03_Ranges.md @@ -56,13 +56,13 @@ Ranges are also useful in `if` statements: fun main() { //sampleStart val x = 2 - if (x in 1..10) { // 1 - print(x) + if (x in 1..5) { // 1 + print("x is in range from 1 to 5") } - print(" ") + println() - if (x !in 1..4) { // 2 - print(x) + if (x !in 6..10) { // 2 + print("x is not in range from 6 to 10") } //sampleEnd } From 0fa5dcff91a943c7ecdd25ad1f20b1daf9735379 Mon Sep 17 00:00:00 2001 From: leeyunhome <59910227+leeyunhome@users.noreply.github.com> Date: Mon, 13 Apr 2020 13:50:53 +0900 Subject: [PATCH 40/95] chore: functions order in 02_Lambdas.md (#103) Although not very relevant to the understanding of the example Listed the numbers of the functions in order. --- examples/04_functional/02_Lambdas.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/04_functional/02_Lambdas.md b/examples/04_functional/02_Lambdas.md index 73c4729..909b1be 100755 --- a/examples/04_functional/02_Lambdas.md +++ b/examples/04_functional/02_Lambdas.md @@ -20,8 +20,8 @@ fun main() { val upperCase6: (String) -> String = String::toUpperCase // 6 - println(upperCase2("hello")) println(upperCase1("hello")) + println(upperCase2("hello")) println(upperCase3("hello")) println(upperCase5("hello")) println(upperCase6("hello")) From d7db58d10c6938c33473dcce0f3e82cdc876af97 Mon Sep 17 00:00:00 2001 From: Pavel Semyonov Date: Mon, 13 Apr 2020 12:00:59 +0700 Subject: [PATCH 41/95] fix: list formatting in 04_Smart Casts.md --- examples/08_productivity_boosters/04_Smart Casts.md | 1 + 1 file changed, 1 insertion(+) diff --git a/examples/08_productivity_boosters/04_Smart Casts.md b/examples/08_productivity_boosters/04_Smart Casts.md index a7e0b82..6a3cf52 100755 --- a/examples/08_productivity_boosters/04_Smart Casts.md +++ b/examples/08_productivity_boosters/04_Smart Casts.md @@ -2,6 +2,7 @@ The Kotlin compiler is smart enough to perform type casts automatically in most cases, including: + 1. Casts from nullable types to their non-nullable counterparts. 2. Casts from a supertype to a subtype. From 897796560d2bfc87a12d24255760af35bfc6f621 Mon Sep 17 00:00:00 2001 From: mohamed rafi <48738678+rafismugmug@users.noreply.github.com> Date: Wed, 22 Jul 2020 21:35:26 -0700 Subject: [PATCH 42/95] chore:better explained function signature for clarity (#108) * better explained function signature for clarity * fix grammar * updated format Co-authored-by: Pavel Semyonov <42832629+p7nov@users.noreply.github.com> Co-authored-by: Pavel Semyonov <42832629+p7nov@users.noreply.github.com> --- examples/04_functional/01_Higher-Order Functions.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/examples/04_functional/01_Higher-Order Functions.md b/examples/04_functional/01_Higher-Order Functions.md index 67cee35..640a616 100755 --- a/examples/04_functional/01_Higher-Order Functions.md +++ b/examples/04_functional/01_Higher-Order Functions.md @@ -39,8 +39,7 @@ fun main() { } ``` -1. Declares a higher-order function that returns a function. +1. Declares a higher-order function that returns a function. `(Int) -> Int` represents the parameters and return type of the `square` function. 2. Declares a function matching the signature. 3. Invokes `operation` to get the result assigned to a variable. Here `func` becomes `square` which is returned by `operation`. 4. Invokes `func`. The `square` function is actually executed. - From a1cc4fa20c2a85ceba45d5a8503c7383ce8d4ca8 Mon Sep 17 00:00:00 2001 From: Brian Hardy Date: Mon, 10 Aug 2020 20:39:43 -0400 Subject: [PATCH 43/95] Clean up partition explanation --- examples/05_Collections/11_partition.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/examples/05_Collections/11_partition.md b/examples/05_Collections/11_partition.md index df24362..c2877a0 100755 --- a/examples/05_Collections/11_partition.md +++ b/examples/05_Collections/11_partition.md @@ -1,8 +1,9 @@ # partition -`partition` function splits the original collection into pair of lists using a given predicate: - * Elements for which the predicate is `true`. - * Elements for which the predicate is `false`. +The `partition` function splits the original collection into a pair of lists using a given predicate: + + 1. Elements for which the predicate is `true`. + 1. Elements for which the predicate is `false`. ```run-kotlin fun main() { From 62761bb655de2c95a02218d802a02b3711bc6d03 Mon Sep 17 00:00:00 2001 From: vincenterc Date: Thu, 13 Aug 2020 13:08:19 +0800 Subject: [PATCH 44/95] chore: step 1 in 02_Set.md (#109) * Update 02_Set.md I think that "comment 1" is on the wrong line, because it say "Adds an element to the `Set`". * Update 02_Set.md --- examples/05_Collections/02_Set.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/05_Collections/02_Set.md b/examples/05_Collections/02_Set.md index 7e83c28..decd2b4 100644 --- a/examples/05_Collections/02_Set.md +++ b/examples/05_Collections/02_Set.md @@ -22,7 +22,7 @@ fun main() { } ``` -1. Adds an element to the `Set`. +1. Creates a `Set` with given elements. 2. Returns a boolean value showing if the element was actually added. 3. Returns a string, based on function input parameter. 4. Prints a success message: the new element is added to the `Set`. From b9ad1f8bf4b441bc2ae3a63bb2b843e6fee38187 Mon Sep 17 00:00:00 2001 From: Aakash Adesara Date: Sun, 13 Sep 2020 22:34:06 -0700 Subject: [PATCH 45/95] fix: remove ternary operator in 04_Equality Checks.md (#111) The next screen (Conditional Expressions) says that Kotlin does not support ternary operators so I believe it does not make sense to use ternary in the description to explain this concept. I would also recommend swapping the Conditional Expressions page and Equality Checks page in the ordering. --- examples/02_control_flow/04_Equality Checks.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/02_control_flow/04_Equality Checks.md b/examples/02_control_flow/04_Equality Checks.md index 43165c6..d4079f6 100755 --- a/examples/02_control_flow/04_Equality Checks.md +++ b/examples/02_control_flow/04_Equality Checks.md @@ -2,7 +2,7 @@ Kotlin uses `==` for structural comparison and `===` for referential comparison. -More precisely, `a == b` compiles down to `a == null ? b == null : a.equals(b)`. +More precisely, `a == b` compiles down to `if (a == null) b == null else a.equals(b)`. ```run-kotlin fun main(args: Array) { From 22476e3e4835e1c514086cbbf7a76e1607b9a093 Mon Sep 17 00:00:00 2001 From: Matt Ranney <71348566+mranney-dd@users.noreply.github.com> Date: Tue, 22 Sep 2020 01:04:22 -0400 Subject: [PATCH 46/95] fix: grammar in 03_Variables.md (#113) grammar fix --- examples/01_introduction/03_Variables.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/01_introduction/03_Variables.md b/examples/01_introduction/03_Variables.md index ac2b958..418cd72 100755 --- a/examples/01_introduction/03_Variables.md +++ b/examples/01_introduction/03_Variables.md @@ -15,9 +15,9 @@ fun main() { } ``` -1. Declares a mutable variable and initializing it. -2. Declares an immutable variable and initializing it. -3. Declares an immutable variable and initializing it without specifying the type. The compiler infers the type `Int`. +1. Declares a mutable variable and initializes it. +2. Declares an immutable variable and initializes it. +3. Declares an immutable variable and initializes it without specifying the type. The compiler infers the type `Int`. ```run-kotlin fun main() { From 5996c26eb1e628ddee81b0e3f4863127533d0c31 Mon Sep 17 00:00:00 2001 From: Matt Ranney <71348566+mranney-dd@users.noreply.github.com> Date: Tue, 22 Sep 2020 18:06:45 -0400 Subject: [PATCH 47/95] Update 03_Map.md Add note about usage of `to` which may be confusing to newcomers. --- examples/05_Collections/03_Map.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/05_Collections/03_Map.md b/examples/05_Collections/03_Map.md index c489307..d2f6908 100644 --- a/examples/05_Collections/03_Map.md +++ b/examples/05_Collections/03_Map.md @@ -1,6 +1,6 @@ # Map -A [map](https://kotlinlang.org/docs/reference/collections.html) is a collection of key/value pairs, where each key is unique and is used to retrieve the corresponding value. For creating maps, there are functions `mapOf()` and `mutableMapOf()`. A read-only view of a mutable map can be obtained by casting it to `Map`. +A [map](https://kotlinlang.org/docs/reference/collections.html) is a collection of key/value pairs, where each key is unique and is used to retrieve the corresponding value. For creating maps, there are functions `mapOf()` and `mutableMapOf()`. Using the [to](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/to.html) infix function makes initialization less noisy. A read-only view of a mutable map can be obtained by casting it to `Map`. ```run-kotlin const val POINTS_X_PASS: Int = 15 From 24c28efdd7d86273d0ad2eec1d659866e8a5dc9d Mon Sep 17 00:00:00 2001 From: Matt Ranney <71348566+mranney-dd@users.noreply.github.com> Date: Tue, 22 Sep 2020 19:40:14 -0400 Subject: [PATCH 48/95] fix list This change seems like it shouldn't be necessary, but it makes the list render properly for me. --- examples/05_Collections/10_associateBy.md | 1 + 1 file changed, 1 insertion(+) diff --git a/examples/05_Collections/10_associateBy.md b/examples/05_Collections/10_associateBy.md index 2b6a2ea..8e12b18 100755 --- a/examples/05_Collections/10_associateBy.md +++ b/examples/05_Collections/10_associateBy.md @@ -4,6 +4,7 @@ Functions `associateBy` and `groupBy` build maps from the elements of a collecti You can also specify an optional `valueSelector` to define what will be stored in the `value` of the map element. The difference between `associateBy` and `groupBy` is how they process objects with the same key: + * `associateBy` uses the last suitable element as the value. * `groupBy` builds a list of all suitable elements and puts it in the value. From c7ef39a2fb42bb0169956a564f5e6afe8d4bebf8 Mon Sep 17 00:00:00 2001 From: Witold Mescheryakov Date: Fri, 2 Oct 2020 20:14:31 +0300 Subject: [PATCH 49/95] Update 04_Object.md Fixed formatting --- examples/03_special_classes/04_Object.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/03_special_classes/04_Object.md b/examples/03_special_classes/04_Object.md index ac414b6..f2b1035 100755 --- a/examples/03_special_classes/04_Object.md +++ b/examples/03_special_classes/04_Object.md @@ -72,7 +72,7 @@ You can also use the `object` **declaration**. It isn't an expression, and can't ```run-kotlin object DoAuth { //1 - fun takeParams(username: String, password: String){ //2 + fun takeParams(username: String, password: String) { //2 println("input Auth parameters = $username:$password") } } From 2962706386d07841b5d5c63d4d30a8921289a656 Mon Sep 17 00:00:00 2001 From: Nikolay Pakudin Date: Sun, 4 Oct 2020 01:32:15 +0300 Subject: [PATCH 50/95] Update 05_Canvas.md Original code fails with errors: Using 'jq(Element): JQuery' is an error. Use declarations from 'https://bintray.com/kotlin/js-externals/kotlin-js-jquery' package instead. Using 'jq(Element): JQuery' is an error. Use declarations from 'https://bintray.com/kotlin/js-externals/kotlin-js-jquery' package instead. Using 'jq(Element): JQuery' is an error. Use declarations from 'https://bintray.com/kotlin/js-externals/kotlin-js-jquery' package instead. Using 'jq(Element): JQuery' is an error. Use declarations from 'https://bintray.com/kotlin/js-externals/kotlin-js-jquery' package instead. Using 'MouseEvent' is an error. Use declarations from 'https://bintray.com/kotlin/js-externals/kotlin-js-jquery' package instead. --- examples/09_Kotlin_JS/05_Canvas.md | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/examples/09_Kotlin_JS/05_Canvas.md b/examples/09_Kotlin_JS/05_Canvas.md index a3f8b0f..3c1ce50 100755 --- a/examples/09_Kotlin_JS/05_Canvas.md +++ b/examples/09_Kotlin_JS/05_Canvas.md @@ -7,10 +7,10 @@ Here strange creatures are watching the kotlin logo. You can drag'n'drop them as ```run-kotlin-canvas package creatures -import jquery.* import org.w3c.dom.* -import kotlin.browser.document -import kotlin.browser.window +import org.w3c.dom.events.MouseEvent +import kotlinx.browser.document +import kotlinx.browser.window import kotlin.math.* @@ -217,10 +217,10 @@ class CanvasState(val canvas: HTMLCanvasElement) { val interval = 1000 / 30 init { - jq(canvas).mousedown { + canvas.onmousedown = { e: MouseEvent -> changed = true selection = null - val mousePos = mousePos(it) + val mousePos = mousePos(e) for (shape in shapes) { if (mousePos in shape) { dragOff = mousePos - shape.pos @@ -231,25 +231,27 @@ class CanvasState(val canvas: HTMLCanvasElement) { } } - jq(canvas).mousemove { + canvas.onmousemove = { e: MouseEvent -> if (selection != null) { - selection!!.pos = mousePos(it) - dragOff + selection!!.pos = mousePos(e) - dragOff changed = true } } - jq(canvas).mouseup { + canvas.onmouseup = { e: MouseEvent -> if (selection != null) { selection!!.selected = false } selection = null changed = true + this } - jq(canvas).dblclick { - val newCreature = Creature(mousePos(it), this@CanvasState) + canvas.ondblclick = { e: MouseEvent -> + val newCreature = Creature(mousePos(e), this@CanvasState) addShape(newCreature) changed = true + this } window.setInterval({ From ddd2df1d8d02eff53cd41a1c97513bc88113a7eb Mon Sep 17 00:00:00 2001 From: Nikolay Pakudin Date: Mon, 5 Oct 2020 22:08:58 +0300 Subject: [PATCH 51/95] fix: http -> https 05_Canvas.md (#119) Kotlin logo isn't shown, because it's loading by http inside of httpS page --- examples/09_Kotlin_JS/05_Canvas.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/09_Kotlin_JS/05_Canvas.md b/examples/09_Kotlin_JS/05_Canvas.md index 3c1ce50..bc9bd37 100755 --- a/examples/09_Kotlin_JS/05_Canvas.md +++ b/examples/09_Kotlin_JS/05_Canvas.md @@ -65,7 +65,7 @@ abstract class Shape() { } } -val logoImage by lazy { getImage("http://try.kotlinlang.org/static/images/kotlin_logo.svg") } +val logoImage by lazy { getImage("https://try.kotlinlang.org/static/images/kotlin_logo.svg") } val logoImageSize = v(120.0, 30.0) @@ -87,7 +87,7 @@ class Logo(override var pos: Vector) : Shape() { } size = logoImageSize * (state.size.x / logoImageSize.x) * relSize - state.context.drawImage(getImage("http://try.kotlinlang.org/static/images/kotlin_logo.svg"), 0.0, 0.0, + state.context.drawImage(getImage("https://try.kotlinlang.org/static/images/kotlin_logo.svg"), 0.0, 0.0, logoImageSize.x, logoImageSize.y, position.x, position.y, size.x, size.y) From 159c7b7057c2b21ab4add5f145170585fb9480dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luiz=20Pican=C3=A7o?= Date: Tue, 13 Oct 2020 00:17:25 -0300 Subject: [PATCH 52/95] feat: add examples for sorted(By)Descending * Update 14_sorted.md Add examples with `sortedDescending` and `sortedByDescending`. * Update 14_sorted.md Add examples with `sortedByDescending` using abs. * Update 14_sorted.md Enhance the description of `sortedByDescending` --- examples/05_Collections/14_sorted.md | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/examples/05_Collections/14_sorted.md b/examples/05_Collections/14_sorted.md index 26d8e3f..ef45fef 100755 --- a/examples/05_Collections/14_sorted.md +++ b/examples/05_Collections/14_sorted.md @@ -5,20 +5,28 @@ `sortedBy` sorts elements according to natural sort order of the values returned by specified selector function. ```run-kotlin +import kotlin.math.abs + fun main() { //sampleStart - val shuffled = listOf(5, 4, 2, 1, 3) // 1 - val natural = shuffled.sorted() // 2 - val inverted = shuffled.sortedBy { -it } // 3 + val shuffled = listOf(5, 4, 2, 1, 3, -10) // 1 + val natural = shuffled.sorted() // 2 + val inverted = shuffled.sortedBy { -it } // 3 + val descending = shuffled.sortedDescending() // 4 + val descendingBy = shuffled.sortedByDescending { abs(it) } // 5 //sampleEnd println("Shuffled: $shuffled") println("Natural order: $natural") println("Inverted natural order: $inverted") + println("Inverted natural order by absolute value: $descending") + println("Inverted natural order of absolute values: $descendingBy") } ``` 1. Defines a collection of shuffled numbers. 2. Sorts it in the natural order. -2. Sorts it in the inverted natural order by using `-it` as a selector function. +3. Sorts it in the inverted natural order by using `-it` as a selector function. +4. Sorts it in the inverted natural order by using `sortedDescending`. +5. Sorts it in the inverted natural order of item's absolute values by using `abs(it)` as a selector function. From 801a71ff0d1edeb86358dbdba645a9ddde42d692 Mon Sep 17 00:00:00 2001 From: Pavel Semyonov Date: Tue, 13 Oct 2020 10:20:29 +0700 Subject: [PATCH 53/95] fix: grammar in 14_sorted.md --- examples/05_Collections/14_sorted.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/05_Collections/14_sorted.md b/examples/05_Collections/14_sorted.md index ef45fef..d75c712 100755 --- a/examples/05_Collections/14_sorted.md +++ b/examples/05_Collections/14_sorted.md @@ -29,4 +29,4 @@ fun main() { 2. Sorts it in the natural order. 3. Sorts it in the inverted natural order by using `-it` as a selector function. 4. Sorts it in the inverted natural order by using `sortedDescending`. -5. Sorts it in the inverted natural order of item's absolute values by using `abs(it)` as a selector function. +5. Sorts it in the inverted natural order of items' absolute values by using `abs(it)` as a selector function. From 00eb03818a84fe37ee239dabe8efe4c3a1a4ae6e Mon Sep 17 00:00:00 2001 From: Deep Patel <31823246+Deep1307@users.noreply.github.com> Date: Mon, 2 Nov 2020 10:50:34 +0530 Subject: [PATCH 54/95] chore: example in 02_Functions.md (#122) * Update 02_Functions.md Added code to print the result of function multiply and accordingly added the documentation line for it. * Update examples/01_introduction/02_Functions.md Suggested changes committed Co-authored-by: Pavel Semyonov <42832629+p7nov@users.noreply.github.com> Co-authored-by: Pavel Semyonov <42832629+p7nov@users.noreply.github.com> --- examples/01_introduction/02_Functions.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/examples/01_introduction/02_Functions.md b/examples/01_introduction/02_Functions.md index c74b18f..f36a3ec 100755 --- a/examples/01_introduction/02_Functions.md +++ b/examples/01_introduction/02_Functions.md @@ -23,6 +23,7 @@ fun main() { printMessageWithPrefix("Hello") // 7 printMessageWithPrefix(prefix = "Log", message = "Hello") // 8 println(sum(1, 2)) // 9 + println(multiply(2, 4)) // 10 } ``` @@ -34,7 +35,8 @@ fun main() { 6. Calls the function with two parameters, passing values for both of them. 7. Calls the same function omitting the second one. The default value `Info` is used. 8. Calls the same function using [named arguments](https://kotlinlang.org/docs/reference/functions.html#named-arguments) and changing the order of the arguments. -9. Prints the result of a function call. +9. Prints the result of the `sum` function call. +10. Prints the result of the `multiply` function call. ### Infix Functions From 03ac2e2728ae002c8e5e786604f745d4dfa05904 Mon Sep 17 00:00:00 2001 From: Vasyl Tretiakov Date: Tue, 17 Nov 2020 07:38:08 +0200 Subject: [PATCH 55/95] update: enhance HTML Builder example (#124) * update kotlin URL * align html builder code with ref doc * optimize imports * remove obsolete args string array in main() fun --- examples/09_Kotlin_JS/06_HtmlBuilder.md | 70 ++++++++++++++++++------- 1 file changed, 51 insertions(+), 19 deletions(-) diff --git a/examples/09_Kotlin_JS/06_HtmlBuilder.md b/examples/09_Kotlin_JS/06_HtmlBuilder.md index 4dc6e79..4afc44e 100755 --- a/examples/09_Kotlin_JS/06_HtmlBuilder.md +++ b/examples/09_Kotlin_JS/06_HtmlBuilder.md @@ -7,11 +7,7 @@ Below is an example of a type-safe Groovy-style builder. In this example, we wil ```run-kotlin-canvas package html -import org.w3c.dom.* -import kotlin.browser.document -import kotlin.browser.window - -fun main(args: Array) { +fun main() { //sampleStart val result = html { // 1 head { // 2 @@ -25,14 +21,14 @@ fun main(args: Array) { } // an element with attributes and text content - a(href = "http://jetbrains.com/kotlin") { +"Kotlin" } + a(href = "http://kotlinlang.org") { +"Kotlin" } // mixed content p { +"This is some" b { +"mixed" } +"text. For more see the" - a(href = "http://jetbrains.com/kotlin") { + a(href = "http://kotlinlang.org") { +"Kotlin" } +"project" @@ -47,25 +43,61 @@ fun main(args: Array) { } } //sampleEnd + println(result) +} + +interface Element { + fun render(builder: StringBuilder, indent: String) +} - document.body!!.appendChild(result.element) +class TextElement(val text: String) : Element { + override fun render(builder: StringBuilder, indent: String) { + builder.append("$indent$text\n") + } } -abstract class Tag(val name: String) { - val element = document.createElement(name) - protected fun initTag(tag: T, init: T.() -> Unit): T { +@DslMarker +annotation class HtmlTagMarker + +@HtmlTagMarker +abstract class Tag(val name: String) : Element { + val children = arrayListOf() + val attributes = hashMapOf() + + protected fun initTag(tag: T, init: T.() -> Unit): T { tag.init() - element.appendChild(tag.element) + children.add(tag) return tag } + + override fun render(builder: StringBuilder, indent: String) { + builder.append("$indent<$name${renderAttributes()}>\n") + for (c in children) { + c.render(builder, indent + " ") + } + builder.append("$indent\n") + } + + private fun renderAttributes(): String { + val builder = StringBuilder() + for ((attr, value) in attributes) { + builder.append(" $attr=\"$value\"") + } + return builder.toString() + } + + override fun toString(): String { + val builder = StringBuilder() + render(builder, "") + return builder.toString() + } } abstract class TagWithText(name: String) : Tag(name) { operator fun String.unaryPlus() { - element.appendChild(document.createTextNode(this + " ")) + children.add(TextElement(this)) } } - class HTML() : TagWithText("html") { fun head(init: Head.() -> Unit) = initTag(Head(), init) fun body(init: Body.() -> Unit) = initTag(Body(), init) @@ -99,11 +131,11 @@ class LI() : BodyTag("li") class P() : BodyTag("p") class H1() : BodyTag("h1") -class A() : BodyTag("a") { - public var href: String - get() = element.getAttribute("href")!! +class A : BodyTag("a") { + var href: String + get() = attributes["href"]!! set(value) { - element.setAttribute("href", value) + attributes["href"] = value } } @@ -125,4 +157,4 @@ fun html(init: HTML.() -> Unit): HTML { 3. Adds the text to tags by calling the `unaryPlus()` operation, like `+"HTML encoding with Kotlin"`. -For details see: [Type Safe Builders](http://kotlinlang.org/docs/reference/type-safe-builders.html) \ No newline at end of file +For details see: [Type Safe Builders](http://kotlinlang.org/docs/reference/type-safe-builders.html) From 63025ae9bcf004374d2b682edefebbf1d3331033 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Aragon=C3=A9s?= <9335325+Darky-Lucera@users.noreply.github.com> Date: Wed, 18 Nov 2020 05:17:07 +0100 Subject: [PATCH 56/95] feat: add example for until in 03_Ranges.md (#128) Added for until --- examples/02_control_flow/03_Ranges.md | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/examples/02_control_flow/03_Ranges.md b/examples/02_control_flow/03_Ranges.md index 276e850..2246e83 100755 --- a/examples/02_control_flow/03_Ranges.md +++ b/examples/02_control_flow/03_Ranges.md @@ -10,12 +10,17 @@ fun main() { } print(" ") - for(i in 2..8 step 2) { // 2 + for(i in 0 until 3) { // 2 print(i) } print(" ") - for (i in 3 downTo 0) { // 3 + for(i in 2..8 step 2) { // 3 + print(i) + } + print(" ") + + for (i in 3 downTo 0) { // 4 print(i) } print(" ") @@ -24,9 +29,10 @@ fun main() { } ``` -1. Iterates over a range starting from 0 up to 3 (inclusive). -2. Iterates over a range with a custom increment step for consecutive elements. -5. Iterates over a range in _reverse_ order. +1. Iterates over a range starting from 0 up to 3 (inclusive). Like 'for(i=0; i<=3; ++i)' in other programming languages (C/C++/Java). +2. Iterates over a range starting from 0 up to 3 (exclusive). Like for loop in Python or like 'for(i=0; i<3; ++i)' in other programming languages (C/C++/Java). +3. Iterates over a range with a custom increment step for consecutive elements. +4. Iterates over a range in _reverse_ order. Char ranges are also supported: From 91679f58590188ebf08f803888ce8ca3c5de4083 Mon Sep 17 00:00:00 2001 From: Sharabaddin Date: Tue, 1 Dec 2020 15:34:00 +0200 Subject: [PATCH 57/95] Update 14_sorted.md mistake --- examples/05_Collections/14_sorted.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/05_Collections/14_sorted.md b/examples/05_Collections/14_sorted.md index d75c712..d1bfda2 100755 --- a/examples/05_Collections/14_sorted.md +++ b/examples/05_Collections/14_sorted.md @@ -20,7 +20,7 @@ fun main() { println("Shuffled: $shuffled") println("Natural order: $natural") println("Inverted natural order: $inverted") - println("Inverted natural order by absolute value: $descending") + println("Inverted natural order value: $descending") println("Inverted natural order of absolute values: $descendingBy") } ``` From 5c06c3ebe53075f7163a3d0dc41bfded103577b3 Mon Sep 17 00:00:00 2001 From: Christopher Schmitz Date: Thu, 17 Dec 2020 22:52:14 -0600 Subject: [PATCH 58/95] update: minOrNull and maxOrNull instead of deprecated min and max (#134) * uses minOrNull and maxOrNull instead of deprecated min and max * Adds java import for absolute value function * removes redundant import * Updates member function names in header and description --- examples/05_Collections/13_max.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/05_Collections/13_max.md b/examples/05_Collections/13_max.md index 49768ce..40c4ed2 100755 --- a/examples/05_Collections/13_max.md +++ b/examples/05_Collections/13_max.md @@ -1,6 +1,6 @@ -# min, max +# minOrNull, maxOrNull -`min` and `max` functions return the smallest and the largest element of a collection. If the collection is empty, they return `null`. +`minOrNull` and `maxOrNull` functions return the smallest and the largest element of a collection. If the collection is empty, they return `null`. ```run-kotlin fun main() { @@ -9,8 +9,8 @@ fun main() { val numbers = listOf(1, 2, 3) val empty = emptyList() - println("Numbers: $numbers, min = ${numbers.min()} max = ${numbers.max()}") // 1 - println("Empty: $empty, min = ${empty.min()}, max = ${empty.max()}") // 2 + println("Numbers: $numbers, min = ${numbers.minOrNull()} max = ${numbers.maxOrNull()}") // 1 + println("Empty: $empty, min = ${empty.minOrNull()}, max = ${empty.maxOrNull()}") // 2 //sampleEnd } ``` From d592ac47ebdfce58fb73cba1b00d7d1e61a35fe2 Mon Sep 17 00:00:00 2001 From: anewway Date: Mon, 4 Jan 2021 11:42:10 +0800 Subject: [PATCH 59/95] Fix inconsistent code according to step description. There maybe some typing error because only the `secondUser` will print the same `hashCode()` with `user`, and the `thirdUser` will not. --- examples/03_special_classes/01_Data classes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/03_special_classes/01_Data classes.md b/examples/03_special_classes/01_Data classes.md index 4b95ae4..fa11968 100755 --- a/examples/03_special_classes/01_Data classes.md +++ b/examples/03_special_classes/01_Data classes.md @@ -16,7 +16,7 @@ fun main() { println("user == thirdUser: ${user == thirdUser}") println(user.hashCode()) // 4 - println(thirdUser.hashCode()) + println(secondUser.hashCode()) // copy() function println(user.copy()) // 5 From 4599bc06bc6aad189d018a16946e8a3b901dc9c6 Mon Sep 17 00:00:00 2001 From: MLNW Date: Sat, 20 Feb 2021 06:42:21 +0100 Subject: [PATCH 60/95] update: maxByOrNull instead of deprecated maxBy (#140) The compiler complained that 'maxBy((T) -> R): T?' is deprecated and should be replaced with maxByOrNull. --- examples/04_functional/03_extensionFunctions.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/examples/04_functional/03_extensionFunctions.md b/examples/04_functional/03_extensionFunctions.md index ac1658e..3bbde43 100755 --- a/examples/04_functional/03_extensionFunctions.md +++ b/examples/04_functional/03_extensionFunctions.md @@ -3,23 +3,23 @@ Kotlin lets you add new members to any class with the [extensions](https://kotlinlang.org/docs/reference/extensions.html) mechanism. Namely, there are two types of extensions: extension functions and extension properties. They look a lot like normal functions and properties but with one important difference: you need to specify the type that you extend. ```run-kotlin -data class Item(val name: String, val price: Float) // 1 +data class Item(val name: String, val price: Float) // 1 data class Order(val items: Collection) -fun Order.maxPricedItemValue(): Float = this.items.maxBy { it.price }?.price ?: 0F // 2 -fun Order.maxPricedItemName() = this.items.maxBy { it.price }?.name ?: "NO_PRODUCTS" +fun Order.maxPricedItemValue(): Float = this.items.maxByOrNull { it.price }?.price ?: 0F // 2 +fun Order.maxPricedItemName() = this.items.maxByOrNull { it.price }?.name ?: "NO_PRODUCTS" -val Order.commaDelimitedItemNames: String // 3 +val Order.commaDelimitedItemNames: String // 3 get() = items.map { it.name }.joinToString() fun main() { val order = Order(listOf(Item("Bread", 25.0F), Item("Wine", 29.0F), Item("Water", 12.0F))) - println("Max priced item name: ${order.maxPricedItemName()}") // 4 + println("Max priced item name: ${order.maxPricedItemName()}") // 4 println("Max priced item value: ${order.maxPricedItemValue()}") - println("Items: ${order.commaDelimitedItemNames}") // 5 + println("Items: ${order.commaDelimitedItemNames}") // 5 } ``` From 54cbcbfca605655fb577ba2e2c83d647c1d7a8b4 Mon Sep 17 00:00:00 2001 From: Homo Efficio Date: Tue, 16 Mar 2021 21:18:20 +0900 Subject: [PATCH 61/95] feat: add example for collection with only one element (#146) --- examples/05_Collections/13_max.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/examples/05_Collections/13_max.md b/examples/05_Collections/13_max.md index 40c4ed2..7a5d5bc 100755 --- a/examples/05_Collections/13_max.md +++ b/examples/05_Collections/13_max.md @@ -8,12 +8,15 @@ fun main() { //sampleStart val numbers = listOf(1, 2, 3) val empty = emptyList() + val only = listOf(3) println("Numbers: $numbers, min = ${numbers.minOrNull()} max = ${numbers.maxOrNull()}") // 1 println("Empty: $empty, min = ${empty.minOrNull()}, max = ${empty.maxOrNull()}") // 2 + println("Only: $only, min = ${only.minOrNull()}, max = ${only.maxOrNull()}") // 3 //sampleEnd } ``` -1. For non-empty collection functions return the smallest and the largest element. -2. For empty collections both functions return `null`. +1. For non-empty collection, functions return the smallest and the largest element. +2. For empty collections, both functions return `null`. +3. For collection with only one element, both functions return the same value. From a398e3fb743e5308227b1151624eec61c777324d Mon Sep 17 00:00:00 2001 From: Homo Efficio Date: Tue, 16 Mar 2021 21:31:33 +0900 Subject: [PATCH 62/95] feat: add an example of associateBy() (#145) Add an example describing the difference between `associateBy()` and `groupBy()` --- examples/05_Collections/10_associateBy.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/examples/05_Collections/10_associateBy.md b/examples/05_Collections/10_associateBy.md index 8e12b18..df02208 100755 --- a/examples/05_Collections/10_associateBy.md +++ b/examples/05_Collections/10_associateBy.md @@ -26,6 +26,7 @@ fun main() { val phoneBook = people.associateBy { it.phone } // 3 val cityBook = people.associateBy(Person::phone, Person::city) // 4 val peopleCities = people.groupBy(Person::city, Person::name) // 5 + val lastPersonCity = people.associateBy(Person::city, Person::name) // 6 //sampleEnd @@ -33,6 +34,7 @@ fun main() { println("Phone book: $phoneBook") println("City book: $cityBook") println("People living in each city: $peopleCities") + println("Last person living in each city: $lastPersonCity") } ``` @@ -41,3 +43,4 @@ fun main() { 3. Builds a map from phone numbers to their owners' information. `it.phone` is the `keySelector` here. The `valueSelector` is not provided, so the values of the map are `Person` objects themselves. 4. Builds a map from phone numbers to the cities where owners live. `Person::city` is the `valueSelector` here, so the values of the map contain only cities. 5. Builds a map that contains cities and people living there. The values of the map are lists of person names. +6. Builds a map that contains cities and the last person living there. The values of the map are names of the last person living in each city. From a48565ced346acd2b4d5ca064c7bce1e4c25a6dd Mon Sep 17 00:00:00 2001 From: Homo Efficio Date: Tue, 16 Mar 2021 21:35:19 +0900 Subject: [PATCH 63/95] fix: example in 01_List.md (#144) addSudoer() actually adds newUser to systemUsers, not sudoers. So it looks better renaming addSudoer() to addSystemUser(). --- examples/05_Collections/01_List.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/05_Collections/01_List.md b/examples/05_Collections/01_List.md index f38816b..362d4d1 100644 --- a/examples/05_Collections/01_List.md +++ b/examples/05_Collections/01_List.md @@ -6,7 +6,7 @@ A [list](https://kotlinlang.org/docs/reference/collections.html) is an ordered c val systemUsers: MutableList = mutableListOf(1, 2, 3) // 1 val sudoers: List = systemUsers // 2 -fun addSudoer(newUser: Int) { // 3 +fun addSystemUser(newUser: Int) { // 3 systemUsers.add(newUser) } @@ -15,7 +15,7 @@ fun getSysSudoers(): List { // 4 } fun main() { - addSudoer(4) // 5 + addSystemUser(4) // 5 println("Tot sudoers: ${getSysSudoers().size}") // 6 getSysSudoers().forEach { // 7 i -> println("Some useful info on user $i") From bb2b4aad7c22bd9d2054e37382633592ad73ef86 Mon Sep 17 00:00:00 2001 From: "MR.HACKER5476" Date: Wed, 24 Mar 2021 13:45:23 +0530 Subject: [PATCH 64/95] update: Add detailed flatMap() example with explanation (#138) * FaltMap: Add detailed example with explanation. * FaltMap: Make code follow kotlin coding conventions --- examples/05_Collections/12_flatMap.md | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/examples/05_Collections/12_flatMap.md b/examples/05_Collections/12_flatMap.md index 742ef3d..8d4286d 100755 --- a/examples/05_Collections/12_flatMap.md +++ b/examples/05_Collections/12_flatMap.md @@ -6,15 +6,20 @@ fun main() { //sampleStart - val numbers = listOf(1, 2, 3) // 1 - - val tripled = numbers.flatMap { listOf(it, it, it) } // 2 + val fruitsBag = listOf("apple","orange","banana","grapes") // 1 + val clothesBag = listOf("shirts","pants","jeans") // 2 + val cart = listOf(fruitsBag, clothesBag) // 3 + val mapBag = cart.map { it } // 4 + val flatMapBag = cart.flatMap { it } // 5 //sampleEnd - println("Numbers: $numbers") - println("Transformed: $tripled") + println("Your bags are: $mapBag") + println("The things you bought are: $flatMapBag") } ``` -1. Defines a collection of numbers. -2. Builds a list in which every collection element is repeated three times. Important thing is that it's **not** a list of lists; it's a list of integers with nine elements. +1. Defines a collection of Strings with fruit names. +2. Defines a collection of Strings with clothes names. +3. Adds `fruitsBag` and `clothesBag` to the `cart` list. +4. Builds a `map` of `cart` elements, which is a list of two lists. +5. Builds a `flatMap` of `cart` elements, which is a single list consisting of elements from both lists. \ No newline at end of file From 92a081f8ffd8e4eae4a9d982a875e8c8d35e2618 Mon Sep 17 00:00:00 2001 From: Gaurang Goda Date: Fri, 14 May 2021 10:01:34 +0530 Subject: [PATCH 65/95] chore: add nested let example (#148) * Added nested let example. Added nested let example which uses name instead of "It". It will be a helpful example when we see nested "let" function, we can not able to access outer let with "it" so I have changed it to named attribute. * improve description Co-authored-by: Pavel Semyonov <42832629+p7nov@users.noreply.github.com> --- examples/06_scope_functions/01_let.md | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/examples/06_scope_functions/01_let.md b/examples/06_scope_functions/01_let.md index 600b0de..118427c 100644 --- a/examples/06_scope_functions/01_let.md +++ b/examples/06_scope_functions/01_let.md @@ -1,11 +1,11 @@ # let The Kotlin standard library function `let` can be used for scoping and null-checks. When called on an object, `let` executes the given block of code and returns the result of its last expression. -The object is accessible inside the block by the reference `it`. +The object is accessible inside the block by the reference `it` (by default) or a custom name. ```run-kotlin fun customPrint(s: String) { - print(s.toUpperCase()) + print(s.uppercase()) } fun main() { @@ -26,13 +26,26 @@ fun main() { println() } } + + fun printIfBothNonNull(strOne: String?, strTwo: String?) { + strOne?.let { firstString -> // 5 + strTwo?.let { secondString -> + customPrint("$firstString : $secondString") + println() + } + } + } + printNonNull(null) printNonNull("my string") + printIfBothNonNull("First","Second") //sampleEnd } + ``` 1. Calls the given block on the result on the string "_test_". 2. Calls the function on "_test_" by the `it` reference. 3. `let` returns the value of this expression. -4. Uses safe call, so `let` and its code block will be executed only on non-null values. +4. Uses safe call, so `let` and its code block will be executed only on non-null values. +5. Uses the custom name instead of `it`, so that the nested `let` can access the context object of the outer `let`. From 0421866d4c358e740b881544df1fec9c223b5f7c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20O=C3=9Fner?= Date: Fri, 14 May 2021 06:45:04 +0200 Subject: [PATCH 66/95] chore: add more details to data_classes.md (#150) * Update 01_Data classes.md I wanted to clarify some things on this page which might help people understand more of the concepts: - Show that the data class can override any default method (such as equals) as well - Make it clear that instances' hashCodes are only equal if they have exactly the same attributes, not if the objects are structurally equal - Show that the copy method really does create a new instance by checking referential equality with the copied object (- Also remove () from one of the hashCodes in the plain text to make it consistent) * chore: improve descriptions Co-authored-by: Pavel Semyonov <42832629+p7nov@users.noreply.github.com> --- .../03_special_classes/01_Data classes.md | 45 +++++++++++-------- 1 file changed, 26 insertions(+), 19 deletions(-) diff --git a/examples/03_special_classes/01_Data classes.md b/examples/03_special_classes/01_Data classes.md index fa11968..336488c 100755 --- a/examples/03_special_classes/01_Data classes.md +++ b/examples/03_special_classes/01_Data classes.md @@ -1,38 +1,45 @@ # Data Classes -[Data classes](https://kotlinlang.org/docs/reference/data-classes.html) make it easy to create classes that are used to store values. Such classes are automatically provided with methods for copying, getting a string representation, and using instances in collections. +[Data classes](https://kotlinlang.org/docs/reference/data-classes.html) make it easy to create classes that are used to store values. Such classes are automatically provided with methods for copying, getting a string representation, and using instances in collections. You can override these methods with your own implementations in the class declaration. ```run-kotlin -data class User(val name: String, val id: Int) // 1 - +data class User(val name: String, val id: Int) { // 1 + override fun equals(other: Any?) = + other is User && other.id == this.id // 2 +} fun main() { val user = User("Alex", 1) - println(user) // 2 + println(user) // 3 val secondUser = User("Alex", 1) val thirdUser = User("Max", 2) - println("user == secondUser: ${user == secondUser}") // 3 + println("user == secondUser: ${user == secondUser}") // 4 println("user == thirdUser: ${user == thirdUser}") - println(user.hashCode()) // 4 + // hashCode() function + println(user.hashCode()) // 5 println(secondUser.hashCode()) + println(thirdUser.hashCode()) // copy() function - println(user.copy()) // 5 - println(user.copy("Max")) // 6 - println(user.copy(id = 2)) // 7 - - println("name = ${user.component1()}") // 8 + println(user.copy()) // 6 + println(user === user.copy()) // 7 + println(user.copy("Max")) // 8 + println(user.copy(id = 3)) // 9 + + println("name = ${user.component1()}") // 10 println("id = ${user.component2()}") } ``` -1. Defines a data class with the `data` modifier. -2. Method `toString` is auto-generated, which makes `println` output look nice. -3. Auto-generated `equals` considers two instances equal if all their properties are equal. -4. Equal data class instances have equal `hashCode()`. -5. Auto-generated `copy` function makes it easy to create a new instance. -6. When copying, you can change values of certain properties. `copy` accepts arguments in the same order as the class constructor. -7. Use `copy` with named arguments to change the value despite of the properties order. -8. Auto-generated `componentN` functions let you get the values of properties in the order of declaration. +1. Defines a data class with the `data` modifier. +2. Override the default `equals` method by declaring users equal if they have the same `id`. +3. Method `toString` is auto-generated, which makes `println` output look nice. +4. Our custom `equals` considers two instances equal if their `id`s are equal. +5. Data class instances with exactly matching attributes have the same `hashCode`. +6. Auto-generated `copy` function makes it easy to create a new instance. +7. `copy` creates a new instance, so the object and its copy have distinct references. +8. When copying, you can change values of certain properties. `copy` accepts arguments in the same order as the class constructor. +9. Use `copy` with named arguments to change the value despite of the properties order. +10. Auto-generated `componentN` functions let you get the values of properties in the order of declaration. From 31f85e4a3c4ffbf376d7e802208a7bb1feea6e3f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20O=C3=9Fner?= Date: Fri, 14 May 2021 06:49:55 +0200 Subject: [PATCH 67/95] chore: add containsRed() check for yellow in enum_classes.md (#151) * Add containsRed() check for yellow This will make it more clear that the operation carried out in containsRed() is a bitwise and operation and not something else. Also, it seems that yellow doesn't really serve a purpose otherwise. * chore: improve description Co-authored-by: Pavel Semyonov <42832629+p7nov@users.noreply.github.com> --- examples/03_special_classes/02_Enum.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/examples/03_special_classes/02_Enum.md b/examples/03_special_classes/02_Enum.md index 3827c6f..a58601a 100755 --- a/examples/03_special_classes/02_Enum.md +++ b/examples/03_special_classes/02_Enum.md @@ -41,6 +41,7 @@ fun main() { println(red) // 4 println(red.containsRed()) // 5 println(Color.BLUE.containsRed()) // 6 + println(Color.YELLOW.containsRed()) // 7 } ``` @@ -51,3 +52,4 @@ fun main() { 4. The default `toString` returns the name of the instance, here `"RED"`. 5. Calls a method on an enum instance. 6. Calls a method via enum class name. +7. The RGB values of `RED` and `YELLOW` share first bits (`FF`) so this prints 'true'. From 34dbcb32ddefc1f9698427415f74cc7777eb79d1 Mon Sep 17 00:00:00 2001 From: vmishenev Date: Thu, 20 May 2021 23:37:24 +0300 Subject: [PATCH 68/95] feat(workflow): add workflow script to verify samples (#154) --- .github/workflows/verify-samples.yml | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 .github/workflows/verify-samples.yml diff --git a/.github/workflows/verify-samples.yml b/.github/workflows/verify-samples.yml new file mode 100644 index 0000000..44099c4 --- /dev/null +++ b/.github/workflows/verify-samples.yml @@ -0,0 +1,24 @@ +name: Verify samples + +on: + push: + branches: [ master ] + pull_request: + branches: [ master ] +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Set up JDK + uses: actions/setup-java@v2 + with: + java-version: '15' + distribution: 'adopt' + - name: Run a verifier + uses: vmishenev/kotlin-samples-pusher@dev + with: + push-repository: 'https://github.com/AlexanderPrendota/kotlin-compiler-server' + tag-filter: '#tag="code" & class="language-run-kotlin"' + push-path: 'src/test/resources/test-compile-data/jvm/kotlin-by-example' + username: '${{ secrets.KOTLIN_BY_EXAMPLE_TOKEN }}' #token with an access to create PR in push-repository and issue in this repository + From a8d0c283528ef252bf004d21c1cd6db1024ae12d Mon Sep 17 00:00:00 2001 From: Alexander Prendota Date: Mon, 24 May 2021 13:55:37 +0300 Subject: [PATCH 69/95] chore(workflow): correct repo --- .github/workflows/verify-samples.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/verify-samples.yml b/.github/workflows/verify-samples.yml index 44099c4..e7801a0 100644 --- a/.github/workflows/verify-samples.yml +++ b/.github/workflows/verify-samples.yml @@ -15,7 +15,7 @@ jobs: java-version: '15' distribution: 'adopt' - name: Run a verifier - uses: vmishenev/kotlin-samples-pusher@dev + uses: AlexanderPrendota/kotlin-samples-pusher@v1 with: push-repository: 'https://github.com/AlexanderPrendota/kotlin-compiler-server' tag-filter: '#tag="code" & class="language-run-kotlin"' From 1bd13f5078887d8747c9e605d31efd5e6282f9dd Mon Sep 17 00:00:00 2001 From: vmishenev Date: Thu, 27 May 2021 17:54:05 +0300 Subject: [PATCH 70/95] chore(samples): mark samples novalidate (#155) --- .github/workflows/verify-samples.yml | 2 +- examples/01_introduction/03_Variables.md | 1 + examples/01_introduction/04_Null Safety.md | 1 + 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/verify-samples.yml b/.github/workflows/verify-samples.yml index e7801a0..8392776 100644 --- a/.github/workflows/verify-samples.yml +++ b/.github/workflows/verify-samples.yml @@ -18,7 +18,7 @@ jobs: uses: AlexanderPrendota/kotlin-samples-pusher@v1 with: push-repository: 'https://github.com/AlexanderPrendota/kotlin-compiler-server' - tag-filter: '#tag="code" & class="language-run-kotlin"' + tag-filter: '#tag="code" & class="language-run-kotlin" & !validate="false"' push-path: 'src/test/resources/test-compile-data/jvm/kotlin-by-example' username: '${{ secrets.KOTLIN_BY_EXAMPLE_TOKEN }}' #token with an access to create PR in push-repository and issue in this repository diff --git a/examples/01_introduction/03_Variables.md b/examples/01_introduction/03_Variables.md index 418cd72..a983dcd 100755 --- a/examples/01_introduction/03_Variables.md +++ b/examples/01_introduction/03_Variables.md @@ -27,6 +27,7 @@ fun main() { //sampleEnd } ``` +{validate="false"} 1. Declares a variable without initialization. 2. An attempt to use the variable causes a compiler error: `Variable 'e' must be initialized`. diff --git a/examples/01_introduction/04_Null Safety.md b/examples/01_introduction/04_Null Safety.md index d8d0aae..5279a9e 100755 --- a/examples/01_introduction/04_Null Safety.md +++ b/examples/01_introduction/04_Null Safety.md @@ -26,6 +26,7 @@ fun main() { //sampleEnd } ``` +{validate="false"} 1. Declares a non-`null` String variable. 2. When trying to assign `null` to non-nullable variable, a compilation error is produced. From 9e39a144d70440c53e5b141f5487d83a51846630 Mon Sep 17 00:00:00 2001 From: Alexander Prendota Date: Fri, 28 May 2021 10:12:20 +0300 Subject: [PATCH 71/95] Revert "chore(samples): mark samples novalidate (#155)" This reverts commit 1bd13f5078887d8747c9e605d31efd5e6282f9dd. --- .github/workflows/verify-samples.yml | 2 +- examples/01_introduction/03_Variables.md | 1 - examples/01_introduction/04_Null Safety.md | 1 - 3 files changed, 1 insertion(+), 3 deletions(-) diff --git a/.github/workflows/verify-samples.yml b/.github/workflows/verify-samples.yml index 8392776..e7801a0 100644 --- a/.github/workflows/verify-samples.yml +++ b/.github/workflows/verify-samples.yml @@ -18,7 +18,7 @@ jobs: uses: AlexanderPrendota/kotlin-samples-pusher@v1 with: push-repository: 'https://github.com/AlexanderPrendota/kotlin-compiler-server' - tag-filter: '#tag="code" & class="language-run-kotlin" & !validate="false"' + tag-filter: '#tag="code" & class="language-run-kotlin"' push-path: 'src/test/resources/test-compile-data/jvm/kotlin-by-example' username: '${{ secrets.KOTLIN_BY_EXAMPLE_TOKEN }}' #token with an access to create PR in push-repository and issue in this repository diff --git a/examples/01_introduction/03_Variables.md b/examples/01_introduction/03_Variables.md index a983dcd..418cd72 100755 --- a/examples/01_introduction/03_Variables.md +++ b/examples/01_introduction/03_Variables.md @@ -27,7 +27,6 @@ fun main() { //sampleEnd } ``` -{validate="false"} 1. Declares a variable without initialization. 2. An attempt to use the variable causes a compiler error: `Variable 'e' must be initialized`. diff --git a/examples/01_introduction/04_Null Safety.md b/examples/01_introduction/04_Null Safety.md index 5279a9e..d8d0aae 100755 --- a/examples/01_introduction/04_Null Safety.md +++ b/examples/01_introduction/04_Null Safety.md @@ -26,7 +26,6 @@ fun main() { //sampleEnd } ``` -{validate="false"} 1. Declares a non-`null` String variable. 2. When trying to assign `null` to non-nullable variable, a compilation error is produced. From 0e2696f9b8acc92b2ac31511f08350e0206e0c6e Mon Sep 17 00:00:00 2001 From: Nikolay Pachkov Date: Thu, 3 Jun 2021 17:53:38 +0300 Subject: [PATCH 72/95] ktl-14 chore: update Kotlin logo --- examples/09_Kotlin_JS/05_Canvas.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/examples/09_Kotlin_JS/05_Canvas.md b/examples/09_Kotlin_JS/05_Canvas.md index bc9bd37..fb64a58 100755 --- a/examples/09_Kotlin_JS/05_Canvas.md +++ b/examples/09_Kotlin_JS/05_Canvas.md @@ -65,11 +65,11 @@ abstract class Shape() { } } -val logoImage by lazy { getImage("https://try.kotlinlang.org/static/images/kotlin_logo.svg") } +val logoImage by lazy { getImage("https://play.kotlinlang.org/assets/kotlin-logo.svg") } -val logoImageSize = v(120.0, 30.0) +val logoImageSize = v(64.0, 64.0) -val Kotlin = Logo(v(canvas.width / 2.0 - logoImageSize.x / 2.0 - 40, canvas.height / 2.0 - logoImageSize.y / 2.0 - 20)) +val Kotlin = Logo(v(canvas.width / 2.0 - logoImageSize.x / 2.0 - 64, canvas.height / 2.0 - logoImageSize.y / 2.0 - 64)) class Logo(override var pos: Vector) : Shape() { val relSize: Double = 0.18 @@ -87,7 +87,7 @@ class Logo(override var pos: Vector) : Shape() { } size = logoImageSize * (state.size.x / logoImageSize.x) * relSize - state.context.drawImage(getImage("https://try.kotlinlang.org/static/images/kotlin_logo.svg"), 0.0, 0.0, + state.context.drawImage(getImage("https://play.kotlinlang.org/assets/kotlin-logo.svg"), 0.0, 0.0, logoImageSize.x, logoImageSize.y, position.x, position.y, size.x, size.y) @@ -353,4 +353,3 @@ fun main(args: Array) { //sampleEnd } ``` - From c2856707e69edf256c954ab77dd043427ec271e4 Mon Sep 17 00:00:00 2001 From: Alexander Prendota Date: Fri, 4 Jun 2021 13:54:39 +0300 Subject: [PATCH 73/95] Revert "Revert "chore(samples): mark samples novalidate (#155)"" This reverts commit 9e39a144d70440c53e5b141f5487d83a51846630. --- .github/workflows/verify-samples.yml | 2 +- examples/01_introduction/03_Variables.md | 1 + examples/01_introduction/04_Null Safety.md | 1 + 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/verify-samples.yml b/.github/workflows/verify-samples.yml index e7801a0..8392776 100644 --- a/.github/workflows/verify-samples.yml +++ b/.github/workflows/verify-samples.yml @@ -18,7 +18,7 @@ jobs: uses: AlexanderPrendota/kotlin-samples-pusher@v1 with: push-repository: 'https://github.com/AlexanderPrendota/kotlin-compiler-server' - tag-filter: '#tag="code" & class="language-run-kotlin"' + tag-filter: '#tag="code" & class="language-run-kotlin" & !validate="false"' push-path: 'src/test/resources/test-compile-data/jvm/kotlin-by-example' username: '${{ secrets.KOTLIN_BY_EXAMPLE_TOKEN }}' #token with an access to create PR in push-repository and issue in this repository diff --git a/examples/01_introduction/03_Variables.md b/examples/01_introduction/03_Variables.md index 418cd72..a983dcd 100755 --- a/examples/01_introduction/03_Variables.md +++ b/examples/01_introduction/03_Variables.md @@ -27,6 +27,7 @@ fun main() { //sampleEnd } ``` +{validate="false"} 1. Declares a variable without initialization. 2. An attempt to use the variable causes a compiler error: `Variable 'e' must be initialized`. diff --git a/examples/01_introduction/04_Null Safety.md b/examples/01_introduction/04_Null Safety.md index d8d0aae..5279a9e 100755 --- a/examples/01_introduction/04_Null Safety.md +++ b/examples/01_introduction/04_Null Safety.md @@ -26,6 +26,7 @@ fun main() { //sampleEnd } ``` +{validate="false"} 1. Declares a non-`null` String variable. 2. When trying to assign `null` to non-nullable variable, a compilation error is produced. From 86506d1090fabc2e01d0a17a39decf656892cc5c Mon Sep 17 00:00:00 2001 From: vmishenev Date: Thu, 27 May 2021 15:08:03 +0300 Subject: [PATCH 74/95] chore(samples): mark samples novalidate --- .github/workflows/verify-samples.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/verify-samples.yml b/.github/workflows/verify-samples.yml index 8392776..ffb2903 100644 --- a/.github/workflows/verify-samples.yml +++ b/.github/workflows/verify-samples.yml @@ -12,10 +12,10 @@ jobs: - name: Set up JDK uses: actions/setup-java@v2 with: - java-version: '15' + java-version: '11' distribution: 'adopt' - name: Run a verifier - uses: AlexanderPrendota/kotlin-samples-pusher@v1 + uses: AlexanderPrendota/kotlin-samples-verifier@master with: push-repository: 'https://github.com/AlexanderPrendota/kotlin-compiler-server' tag-filter: '#tag="code" & class="language-run-kotlin" & !validate="false"' From 100c7c80a2240b3614e89feafaa91bbcf029787c Mon Sep 17 00:00:00 2001 From: Aleksandr Fedotov Date: Fri, 4 Jun 2021 23:00:47 +0300 Subject: [PATCH 75/95] Update 01_Hello world.md Replaced word to more suitable --- examples/01_introduction/01_Hello world.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/01_introduction/01_Hello world.md b/examples/01_introduction/01_Hello world.md index a0795bc..53ca52a 100755 --- a/examples/01_introduction/01_Hello world.md +++ b/examples/01_introduction/01_Hello world.md @@ -9,7 +9,7 @@ fun main() { // 2 ``` 1. Kotlin code is usually defined in packages. Package specification is optional: If you don't specify a package in a source file, its content goes to the default package. -2. An entry point to a Kotlin application is the `main` function. In Kotlin 1.3, you can declare `main` without any parameters. The return type is not specified, which means that the function returns nothing. +2. An entry point to a Kotlin application is the `main` function. Since Kotlin 1.3, you can declare `main` without any parameters. The return type is not specified, which means that the function returns nothing. 3. `println` writes a line to the standard output. It is imported implicitly. Also note that semicolons are optional. In Kotlin versions earlier than 1.3, the `main` function must have a parameter of type `Array`. From 6a2108e9ecf7a107b468ea9527372baabbd92d00 Mon Sep 17 00:00:00 2001 From: Zachary Grafton Date: Tue, 22 Jun 2021 23:16:42 -0400 Subject: [PATCH 76/95] update: sealed classes location in Kotlin 1.5 (#162) According to https://kotlinlang.org/docs/whatsnew15.html#package-wide-sealed-class-hierarchies sealed classes no longer need to be in the same file, but are still restricted to the same package. --- examples/03_special_classes/03_Sealed Classes.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/03_special_classes/03_Sealed Classes.md b/examples/03_special_classes/03_Sealed Classes.md index 01a6d6e..f659477 100755 --- a/examples/03_special_classes/03_Sealed Classes.md +++ b/examples/03_special_classes/03_Sealed Classes.md @@ -1,6 +1,6 @@ # Sealed Classes -[Sealed classes](https://kotlinlang.org/docs/reference/sealed-classes.html) let you restrict the use of inheritance. Once you declare a class sealed, it can only be subclassed from inside the same file where the sealed class is declared. It cannot be subclassed outside of the file where the sealed class is declared. +[Sealed classes](https://kotlinlang.org/docs/reference/sealed-classes.html) let you restrict the use of inheritance. Once you declare a class sealed, it can only be subclassed from inside the same package where the sealed class is declared. It cannot be subclassed outside of the package where the sealed class is declared. ```run-kotlin sealed class Mammal(val name: String) // 1 @@ -21,7 +21,7 @@ fun main() { ``` 1. Defines a sealed class. -2. Defines subclasses. Note that all subclasses must be in the same file. +2. Defines subclasses. Note that all subclasses must be in the same package. 3. Uses an instance of the sealed class as an argument in a `when` expression. 4. A smartcast is performed, casting `Mammal` to `Human`. 5. A smartcast is performed, casting `Mammal` to `Cat`. From 9a9aafe7a436c436b68ec35937587470cd967146 Mon Sep 17 00:00:00 2001 From: BlinkovX <87264036+BlinkovX@users.noreply.github.com> Date: Mon, 12 Jul 2021 07:12:23 +0300 Subject: [PATCH 77/95] chore: toUpperCase() is deprecated (#163) In last versions of Kotlin method 'toUpperCase()' is deprecated, but you can use 'uppercase()' method --- examples/04_functional/02_Lambdas.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/examples/04_functional/02_Lambdas.md b/examples/04_functional/02_Lambdas.md index 909b1be..13acd33 100755 --- a/examples/04_functional/02_Lambdas.md +++ b/examples/04_functional/02_Lambdas.md @@ -8,17 +8,17 @@ fun main() { // All examples create a function object that performs upper-casing. // So it's a function from String to String - val upperCase1: (String) -> String = { str: String -> str.toUpperCase() } // 1 + val upperCase1: (String) -> String = { str: String -> str.uppercase() } // 1 - val upperCase2: (String) -> String = { str -> str.toUpperCase() } // 2 + val upperCase2: (String) -> String = { str -> str.uppercase() } // 2 - val upperCase3 = { str: String -> str.toUpperCase() } // 3 + val upperCase3 = { str: String -> str.uppercase() } // 3 - // val upperCase4 = { str -> str.toUpperCase() } // 4 + // val upperCase4 = { str -> str.uppercase() } // 4 - val upperCase5: (String) -> String = { it.toUpperCase() } // 5 + val upperCase5: (String) -> String = { it.uppercase() } // 5 - val upperCase6: (String) -> String = String::toUpperCase // 6 + val upperCase6: (String) -> String = String::uppercase // 6 println(upperCase1("hello")) println(upperCase2("hello")) From 8d511780f65355aa9305d885f0293eaa6820b2e5 Mon Sep 17 00:00:00 2001 From: Joykishan Sharma Date: Mon, 19 Jul 2021 11:01:29 +0530 Subject: [PATCH 78/95] chore: remove redundant args in 04_Equality Checks.md (#152) 'args' parameter is redundant --- examples/02_control_flow/04_Equality Checks.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/02_control_flow/04_Equality Checks.md b/examples/02_control_flow/04_Equality Checks.md index d4079f6..c5e316f 100755 --- a/examples/02_control_flow/04_Equality Checks.md +++ b/examples/02_control_flow/04_Equality Checks.md @@ -5,7 +5,7 @@ Kotlin uses `==` for structural comparison and `===` for referential comparison. More precisely, `a == b` compiles down to `if (a == null) b == null else a.equals(b)`. ```run-kotlin -fun main(args: Array) { +fun main() { //sampleStart val authors = setOf("Shakespeare", "Hemingway", "Twain") From a65b36e699bb6aa73cb5ee8ca3f530c7e597a154 Mon Sep 17 00:00:00 2001 From: Jean-Louis GUENEGO Date: Mon, 19 Jul 2021 06:32:06 +0100 Subject: [PATCH 79/95] fix: there is not a such thing as "enum instance" (#164) * fix: there is not a such thing as "enum instance" Enum are like static classes. There is no instance. * fix: replace enum instance with constant Co-authored-by: Pavel Semyonov <42832629+p7nov@users.noreply.github.com> --- examples/03_special_classes/02_Enum.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/examples/03_special_classes/02_Enum.md b/examples/03_special_classes/02_Enum.md index a58601a..415346b 100755 --- a/examples/03_special_classes/02_Enum.md +++ b/examples/03_special_classes/02_Enum.md @@ -19,11 +19,11 @@ fun main() { ``` -1. Defines a simple enum class with three enum instances. The number of instances is always finite and they are all distinct. -2. Accesses an enum instance via the class name. +1. Defines a simple enum class with three enum constants. The number of constants is always finite and they are all distinct. +2. Accesses an enum constant via the class name. 3. With enums, the compiler can infer if a `when`-expression is exhaustive so that you don't need the `else`-case. -Enums may contain properties and methods like other classes, separated from the list of instances by a semicolon. +Enums may contain properties and methods like other classes, separated from the list of enum constants by a semicolon. ```run-kotlin @@ -47,9 +47,9 @@ fun main() { ``` 1. Defines an enum class with a property and a method. -2. Each instance must pass an argument for the constructor parameter. -3. Enum class members are separated from the instance definitions by a semicolon. -4. The default `toString` returns the name of the instance, here `"RED"`. -5. Calls a method on an enum instance. +2. Each enum constant must pass an argument for the constructor parameter. +3. Enum class members are separated from the constant definitions by a semicolon. +4. The default `toString` returns the name of the constant, here `"RED"`. +5. Calls a method on an enum constant. 6. Calls a method via enum class name. 7. The RGB values of `RED` and `YELLOW` share first bits (`FF`) so this prints 'true'. From a9f7a7e167c90f4fa53b6038a223197d3e0a55a3 Mon Sep 17 00:00:00 2001 From: Fabian Neugart Date: Tue, 9 Nov 2021 22:33:08 +0100 Subject: [PATCH 80/95] Added missing possessive adjective --- examples/05_Collections/16_zip.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/05_Collections/16_zip.md b/examples/05_Collections/16_zip.md index 9c9901d..5b8297b 100755 --- a/examples/05_Collections/16_zip.md +++ b/examples/05_Collections/16_zip.md @@ -1,6 +1,6 @@ # zip -`zip` function merges two given collections into a new collection. By default, the result collection contains `Pairs` of source collection elements with the same index. However, you can define own structure of the result collection element. +`zip` function merges two given collections into a new collection. By default, the result collection contains `Pairs` of source collection elements with the same index. However, you can define your own structure of the result collection element. The size of the result collection equals to the minimum size of a source collection. From 80517e2ce8da32c8fde205ad7b09a4977a3c97df Mon Sep 17 00:00:00 2001 From: yanxiaoseng <48822103+yanxiaoseng@users.noreply.github.com> Date: Mon, 17 Jan 2022 12:10:30 +0800 Subject: [PATCH 81/95] chore: better descriptions in 07_firstlast.md (#174) * Update 07_firstlast.md * Update 07_firstlast.md Co-authored-by: Pavel Semyonov <42832629+p7nov@users.noreply.github.com> --- examples/05_Collections/07_firstlast.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/05_Collections/07_firstlast.md b/examples/05_Collections/07_firstlast.md index 9c9b920..bf3b785 100755 --- a/examples/05_Collections/07_firstlast.md +++ b/examples/05_Collections/07_firstlast.md @@ -50,9 +50,9 @@ fun main() { val lastZ = words.lastOrNull { it.endsWith('z') } // 8 //sampleEnd - println("First $first, last $last") - println("First starts with 'f' is $firstF, last starts with 'z' is $firstZ") - println("First ends with 'f' is $lastF, last ends with 'z' is $lastZ") + println("Empty list: first is $first, last is $last") + println("Word list: first item starting with 'f' is $firstF, first item starting with 'z' is $firstZ") + println("Word list: last item ending with 'f' is $lastF, last item ending with 'z' is $lastZ") } ``` From d56332e19e9dcc697d9b7db825aa00584067aa3d Mon Sep 17 00:00:00 2001 From: Prat T Date: Sat, 20 Aug 2022 12:20:47 -0700 Subject: [PATCH 82/95] fix: typo in Kotlin JS Canvas example --- examples/09_Kotlin_JS/05_Canvas.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/09_Kotlin_JS/05_Canvas.md b/examples/09_Kotlin_JS/05_Canvas.md index fb64a58..81ad253 100755 --- a/examples/09_Kotlin_JS/05_Canvas.md +++ b/examples/09_Kotlin_JS/05_Canvas.md @@ -20,9 +20,9 @@ fun getImage(path: String): HTMLImageElement { return image } -val canvas = initalizeCanvas() +val canvas = initializeCanvas() -fun initalizeCanvas(): HTMLCanvasElement { +fun initializeCanvas(): HTMLCanvasElement { val canvas = document.createElement("canvas") as HTMLCanvasElement val context = canvas.getContext("2d") as CanvasRenderingContext2D context.canvas.width = window.innerWidth.toInt() From 24abc7ceeea3280a35de052cc3fbbb4b3f9d1781 Mon Sep 17 00:00:00 2001 From: Mert <57791061+mertsancar@users.noreply.github.com> Date: Wed, 28 Sep 2022 15:53:39 +0300 Subject: [PATCH 83/95] Update 02_String Templates.md --- examples/08_productivity_boosters/02_String Templates.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/08_productivity_boosters/02_String Templates.md b/examples/08_productivity_boosters/02_String Templates.md index a2f85cf..a9b31d0 100755 --- a/examples/08_productivity_boosters/02_String Templates.md +++ b/examples/08_productivity_boosters/02_String Templates.md @@ -8,7 +8,7 @@ fun main() { val greeting = "Kotliner" println("Hello $greeting") // 1 - println("Hello ${greeting.toUpperCase()}") // 2 + println("Hello ${greeting.uppercase()}") // 2 //sampleEnd } ``` From 5f74dd3f4fceaba2462badfebc735c31a0902a7e Mon Sep 17 00:00:00 2001 From: Danny Date: Thu, 6 Oct 2022 15:17:55 +0200 Subject: [PATCH 84/95] Update 01_When.md use number instead on name for "1". --- examples/02_control_flow/01_When.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/02_control_flow/01_When.md b/examples/02_control_flow/01_When.md index 53b28b1..3471137 100755 --- a/examples/02_control_flow/01_When.md +++ b/examples/02_control_flow/01_When.md @@ -27,7 +27,7 @@ class MyClass ``` 1. This is a `when` statement. -2. Checks whether `obj` equals to one. +2. Checks whether `obj` equals to "1". 3. Checks whether `obj` equals to `Hello`. 4. Performs type checking. 5. Performs inverse type checking. @@ -60,7 +60,7 @@ class MyClass 1. This is a `when` expression. -2. Sets the value to `"one"` if `obj` equals to one. +2. Sets the value to `"one"` if `obj` equals to "1". 3. Sets the value to one if `obj` equals to `Hello`. 4. Sets the value to `false` if `obj` is an instance of `Long`. 5. Sets the value "42" if none of the previous conditions are satisfied. Unlike in `when` _statement_, the default branch is usually required in `when` _expression_, except the case when the compiler can check that other branches cover all possible cases. From 40f34017e4799835afe6fce1524a913831f7c6a4 Mon Sep 17 00:00:00 2001 From: Danny Date: Mon, 10 Oct 2022 11:01:33 +0200 Subject: [PATCH 85/95] Update 01_When.md * put Strings in quotes * remove quotes from numbers --- examples/02_control_flow/01_When.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/02_control_flow/01_When.md b/examples/02_control_flow/01_When.md index 3471137..558890b 100755 --- a/examples/02_control_flow/01_When.md +++ b/examples/02_control_flow/01_When.md @@ -27,8 +27,8 @@ class MyClass ``` 1. This is a `when` statement. -2. Checks whether `obj` equals to "1". -3. Checks whether `obj` equals to `Hello`. +2. Checks whether `obj` equals to `1`. +3. Checks whether `obj` equals to `"Hello"`. 4. Performs type checking. 5. Performs inverse type checking. 6. Default statement (might be omitted). @@ -60,7 +60,7 @@ class MyClass 1. This is a `when` expression. -2. Sets the value to `"one"` if `obj` equals to "1". -3. Sets the value to one if `obj` equals to `Hello`. +2. Sets the value to `"one"` if `obj` equals to `1`. +3. Sets the value to one if `obj` equals to `"Hello"`. 4. Sets the value to `false` if `obj` is an instance of `Long`. -5. Sets the value "42" if none of the previous conditions are satisfied. Unlike in `when` _statement_, the default branch is usually required in `when` _expression_, except the case when the compiler can check that other branches cover all possible cases. +5. Sets the value `42` if none of the previous conditions are satisfied. Unlike in `when` _statement_, the default branch is usually required in `when` _expression_, except the case when the compiler can check that other branches cover all possible cases. From 350221d7cf46c38e0032983f8875920f03f1d7d7 Mon Sep 17 00:00:00 2001 From: oohira Date: Wed, 23 Nov 2022 11:35:59 +0900 Subject: [PATCH 86/95] Fix indentation of sample code comment --- examples/08_productivity_boosters/02_String Templates.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/08_productivity_boosters/02_String Templates.md b/examples/08_productivity_boosters/02_String Templates.md index a9b31d0..842e226 100755 --- a/examples/08_productivity_boosters/02_String Templates.md +++ b/examples/08_productivity_boosters/02_String Templates.md @@ -8,7 +8,7 @@ fun main() { val greeting = "Kotliner" println("Hello $greeting") // 1 - println("Hello ${greeting.uppercase()}") // 2 + println("Hello ${greeting.uppercase()}") // 2 //sampleEnd } ``` From a72671fd009e267bd147bb95c83f848443a71eb3 Mon Sep 17 00:00:00 2001 From: Harshit Pandey Date: Sun, 18 Dec 2022 09:59:56 +0530 Subject: [PATCH 87/95] Update 02_Functions.md Added example for special spread operator at line 124. --- examples/01_introduction/02_Functions.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/examples/01_introduction/02_Functions.md b/examples/01_introduction/02_Functions.md index f36a3ec..0e41378 100755 --- a/examples/01_introduction/02_Functions.md +++ b/examples/01_introduction/02_Functions.md @@ -120,6 +120,8 @@ fun main() { fun log(vararg entries: String) { printAll(*entries) // 5 } + + log("Hello", "Hallo", "Salut", "Hola", "你好") //sampleEnd } ``` From 22f99626d11779473a6482793860b885cac7f418 Mon Sep 17 00:00:00 2001 From: Sebastian Aigner Date: Thu, 5 Jan 2023 11:27:56 +0100 Subject: [PATCH 88/95] Remove extraneous newline to keep formatting consistent --- examples/01_introduction/02_Functions.md | 1 - 1 file changed, 1 deletion(-) diff --git a/examples/01_introduction/02_Functions.md b/examples/01_introduction/02_Functions.md index 0e41378..216941d 100755 --- a/examples/01_introduction/02_Functions.md +++ b/examples/01_introduction/02_Functions.md @@ -120,7 +120,6 @@ fun main() { fun log(vararg entries: String) { printAll(*entries) // 5 } - log("Hello", "Hallo", "Salut", "Hola", "你好") //sampleEnd } From 2f508291a47420326fe1fa65ea278a3ff6619e67 Mon Sep 17 00:00:00 2001 From: Mark Grand Date: Mon, 17 Apr 2023 20:48:31 -0400 Subject: [PATCH 89/95] Update 06_find.md --- examples/05_Collections/06_find.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/05_Collections/06_find.md b/examples/05_Collections/06_find.md index 34ac8d9..b0043ec 100755 --- a/examples/05_Collections/06_find.md +++ b/examples/05_Collections/06_find.md @@ -1,6 +1,6 @@ # find, findLast -`find` and `findLast` functions return the first or the last collection element that matches the given predicate. If there are no such elements, functions return `null`. +The `find` and `findLast` functions return the first or the last collection element that matches the given predicate. If there are no such elements, these functions return `null`. ```run-kotlin From 87dfd9122dfe6092f5b2ada9611db29f0a4cc98a Mon Sep 17 00:00:00 2001 From: Hoang Pham Date: Sun, 18 Jun 2023 10:16:34 +0200 Subject: [PATCH 90/95] Update 01_delegationPattern.md --- examples/07_Delegation/01_delegationPattern.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/07_Delegation/01_delegationPattern.md b/examples/07_Delegation/01_delegationPattern.md index 3b8db37..4b5b27e 100755 --- a/examples/07_Delegation/01_delegationPattern.md +++ b/examples/07_Delegation/01_delegationPattern.md @@ -8,7 +8,7 @@ interface SoundBehavior { } class ScreamBehavior(val n:String): SoundBehavior { // 2 - override fun makeSound() = println("${n.toUpperCase()} !!!") + override fun makeSound() = println("${n.uppercase()} !!!") } class RockAndRollBehavior(val n:String): SoundBehavior { // 2 From 0e614d4431092ad6d1ffb0f0e3510db9e9b5eb48 Mon Sep 17 00:00:00 2001 From: Sarah Haggarty Date: Tue, 28 Nov 2023 10:56:03 +0100 Subject: [PATCH 91/95] Add JetBrains official badge to Readme --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 2f4facf..dafc99d 100755 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ # Kotlin by Example +[![official JetBrains project](https://jb.gg/badges/official-plastic.svg)](https://github.com/JetBrains#jetbrains-on-github) This is sources of [Kotlin Examples](https://play.kotlinlang.org/byExample/overview). From a5f7ebd7c15b49f94e6688055c8b59e827629235 Mon Sep 17 00:00:00 2001 From: Aleksey Zamulla Date: Mon, 25 Mar 2024 13:14:31 +0400 Subject: [PATCH 92/95] update: remove Kotlin 1.3 references --- examples/01_introduction/01_Hello world.md | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/examples/01_introduction/01_Hello world.md b/examples/01_introduction/01_Hello world.md index 53ca52a..fed021f 100755 --- a/examples/01_introduction/01_Hello world.md +++ b/examples/01_introduction/01_Hello world.md @@ -9,14 +9,6 @@ fun main() { // 2 ``` 1. Kotlin code is usually defined in packages. Package specification is optional: If you don't specify a package in a source file, its content goes to the default package. -2. An entry point to a Kotlin application is the `main` function. Since Kotlin 1.3, you can declare `main` without any parameters. The return type is not specified, which means that the function returns nothing. -3. `println` writes a line to the standard output. It is imported implicitly. Also note that semicolons are optional. - -In Kotlin versions earlier than 1.3, the `main` function must have a parameter of type `Array`. - -```run-kotlin -fun main(args: Array) { - println("Hello, World!") -} -``` +2. An entry point to a Kotlin application is the `main` function. You can declare it without any parameters. The return type is not specified, which means that the function returns nothing. +3. `println` writes a line to the standard output. It is imported implicitly. Also, note that semicolons at the end of code lines are optional. From d5f93bbdcbb5530214c423ee7bd1ef8fdbaf490a Mon Sep 17 00:00:00 2001 From: Hubert Skrzypczak Date: Mon, 6 Jan 2025 20:39:51 +0100 Subject: [PATCH 93/95] Fix formatting --- examples/07_Delegation/01_delegationPattern.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/07_Delegation/01_delegationPattern.md b/examples/07_Delegation/01_delegationPattern.md index 4b5b27e..9f396da 100755 --- a/examples/07_Delegation/01_delegationPattern.md +++ b/examples/07_Delegation/01_delegationPattern.md @@ -7,19 +7,19 @@ interface SoundBehavior { fun makeSound() } -class ScreamBehavior(val n:String): SoundBehavior { // 2 +class ScreamBehavior(val n: String): SoundBehavior { // 2 override fun makeSound() = println("${n.uppercase()} !!!") } -class RockAndRollBehavior(val n:String): SoundBehavior { // 2 +class RockAndRollBehavior(val n: String): SoundBehavior { // 2 override fun makeSound() = println("I'm The King of Rock 'N' Roll: $n") } // Tom Araya is the "singer" of Slayer -class TomAraya(n:String): SoundBehavior by ScreamBehavior(n) // 3 +class TomAraya(n: String): SoundBehavior by ScreamBehavior(n) // 3 // You should know ;) -class ElvisPresley(n:String): SoundBehavior by RockAndRollBehavior(n) // 3 +class ElvisPresley(n: String): SoundBehavior by RockAndRollBehavior(n) // 3 fun main() { val tomAraya = TomAraya("Thrash Metal") From 6f82d05d9c67445e4f48c981c361e11a29d037af Mon Sep 17 00:00:00 2001 From: Nikolai Pachkov Date: Fri, 10 Oct 2025 10:03:19 +0200 Subject: [PATCH 94/95] Update README.md --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index dafc99d..b4b16ae 100755 --- a/README.md +++ b/README.md @@ -1,7 +1,9 @@ # Kotlin by Example -[![official JetBrains project](https://jb.gg/badges/official-plastic.svg)](https://github.com/JetBrains#jetbrains-on-github) +[![Obsolete JetBrains project](http://jb.gg/badges/obsolete.svg)](https://confluence.jetbrains.com/display/ALL/JetBrains+on+GitHub) -This is sources of [Kotlin Examples](https://play.kotlinlang.org/byExample/overview). +Please refer to [Kotlin Tour](https://kotlinlang.org/docs/kotlin-tour-welcome.html) for up-to-date Kotlin learning materials. + +------------ ### How to make example From 1fb7ef4774547b5372798050c8557e1f98f21fd9 Mon Sep 17 00:00:00 2001 From: Nikolai Pachkov Date: Fri, 10 Oct 2025 10:04:19 +0200 Subject: [PATCH 95/95] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b4b16ae..6303c49 100755 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Kotlin by Example [![Obsolete JetBrains project](http://jb.gg/badges/obsolete.svg)](https://confluence.jetbrains.com/display/ALL/JetBrains+on+GitHub) -Please refer to [Kotlin Tour](https://kotlinlang.org/docs/kotlin-tour-welcome.html) for up-to-date Kotlin learning materials. +The repository is archived, please refer to [Kotlin Tour](https://kotlinlang.org/docs/kotlin-tour-welcome.html) for up-to-date Kotlin learning materials. ------------