Kotlin #kotlin Table of Contents About Chapter 1: Getting started with Kotlin Remarks Compiling Kotlin Versions Examples Hello World Hello World using an Object Declaration Hello World using a Companion Object Main methods using varargs Compile and Run Kotlin Code in Command Line Reading input from Command Line Chapter 2: Annotations Examples Declaring an annotation Meta-annotations Chapter 3: Arrays Examples Generic Arrays Arrays of Primitives Extensions Iterate Array Create an array Create an array using a closure Create an uninitialized array Chapter 4: Basic Lambdas Syntax Remarks Examples Lambda as parameter to filter function 1 2 2 2 2 3 3 3 4 5 5 5 7 7 7 7 9 9 9 9 10 10 10 10 11 12 12 12 13 13 Lambda passed as a variable Lambda for benchmarking a function call Chapter 5: Basics of Kotlin Introduction Remarks Examples Basic examples Chapter 6: Class Delegation Introduction Examples Delegate a method to another class Chapter 7: Class Inheritance Introduction Syntax Parameters Examples Basics: the 'open' keyword Inheriting fields from a class Defining the base class: Defining the derived class: Using the subclass: Inheriting methods from a class Defining the base class: Defining the derived class: The Ninja has access to all of the methods in Person Overriding properties and methods Overriding properties (both read-only and mutable): Overriding methods: Chapter 8: Collections Introduction Syntax Examples 13 13 14 14 14 14 14 16 16 16 16 17 17 17 17 17 17 18 18 18 18 18 18 18 18 19 19 19 20 20 20 20 Using list Using map Using set Chapter 9: Conditional Statements Remarks Examples Standard if-statement If-statement as an expression When-statement instead of if-else-if chains When-statement argument matching When-statement as expression When-statement with enums Chapter 10: Configuring Kotlin build Examples Gradle configuration Targeting JVM Targeting Android Targeting JS Using Android Studio Install the plugin Configure a project Converting Java Migrating from Gradle using Groovy script to Kotlin script Chapter 11: coroutines Introduction Examples Simple coroutine which delay's 1 second but not blocks Chapter 12: Delegated properties Introduction Examples Lazy initialization Observable properties 20 20 20 21 21 21 21 21 22 22 23 23 25 25 25 25 25 25 26 26 26 26 27 29 29 29 29 30 30 30 30 30 Map-backed properties Custom delegation Delegate Can be used as a layer to reduce boilerplate Chapter 13: DSL Building Introduction Examples Infix approach to build DSL Overriding invoke method to build DSL Using operators with lambdas Using extensions with lambdas Chapter 14: Enum Remarks Examples Initialization Functions and Properties in enums Simple enum Mutability Chapter 15: Exceptions Examples Catching exception with try-catch-finally Chapter 16: Extension Methods Syntax Remarks Examples Top-Level Extensions Potential Pitfall: Extensions are Resolved Statically Sample extending long to render a human readable string Sample extending Java 7+ Path class Using extension functions to improve readability Sample extending Java 8 Temporal classes to render an ISO formatted string Extension functions to Companion Objects (appearance of Static functions) Lazy extension property workaround 30 30 31 33 33 33 33 33 33 34 35 35 35 35 35 36 36 37 37 37 38 38 38 38 38 38 39 39 39 40 40 41 Extensions for easier reference View from code Extensions Usage Chapter 17: Functions Syntax Parameters Examples Functions Taking Other Functions Lambda Functions Function References Basic Functions Shorthand Functions Inline Functions Operator functions Chapter 18: Generics Introduction Syntax Parameters Remarks Implied Upper Bound is Nullable Examples Declaration-site variance Use-site variance Chapter 19: Idioms Examples Creating DTOs (POJOs/POCOs) Filtering a list Delegate to a class without providing it in the public constructor Serializable and serialVersionUid in Kotlin Fluent methods in Kotlin Use let or also to simplify working with nullable objects Use apply to initialize objects or to achieve method chaining 41 41 42 43 43 43 43 43 44 44 46 46 46 47 48 48 48 48 48 48 49 49 49 51 51 51 51 51 52 52 53 53 Chapter 20: Interfaces Remarks Examples Basic Interface Interface with default implementations Properties Multiple implementations Properties in Interfaces Conflicts when Implementing Multiple Interfaces with Default Implementations super keyword Chapter 21: Java 8 Stream Equivalents Introduction Remarks About laziness Why are there no Types?!? Reusing Streams See also: Examples Accumulate names in a List Convert elements to strings and concatenate them, separated by commas Compute sum of salaries of employee Group employees by department Compute sum of salaries by department Partition students into passing and failing Names of male members Group names of members in roster by gender Filter a list to another list Finding shortest string a list Different Kinds of Streams #2 - lazily using first item if exists Different Kinds of Streams #3 - iterate a range of Integers Different Kinds of Streams #4 - iterate an array, map the values, calculate the average Different Kinds of Streams #5 - lazily iterate a list of strings, map the values, convert 55 55 55 55 55 55 56 56 57 57 59 59 59 59 59 60 60 61 61 61 61 61 61 62 62 62 62 62 63 63 63 63 Different Kinds of Streams #6 - lazily iterate a stream of Ints, map the values, print res Different Kinds of Streams #7 - lazily iterate Doubles, map to Int, map to String, print e Counting items in a list after filter is applied How streams work - filter, upper case, then sort a list Different Kinds of Streams #1 - eager using first item if it exists Collect example #5 - find people of legal age, output formatted string Collect example #6 - group people by age, print age and names together Collect example #7a - Map names, join together with delimiter Collect example #7b - Collect with SummarizingInt Chapter 22: JUnit Examples Rules Chapter 23: Kotlin Android Extensions Introduction Examples Configuration Using Views Product flavors Painfull listener for getting notice, when the view is completely drawn now is so simple a Chapter 24: Kotlin Caveats Examples Calling a toString() on a nullable type Chapter 25: Kotlin for Java Developers Introduction Examples Declaring Variables Quick Facts Equality & Identity IF, TRY and others are expressions, not statements Chapter 26: logging in kotlin Remarks Examples 64 64 64 64 65 65 66 67 67 69 69 69 70 70 70 70 70 71 72 73 73 73 74 74 74 74 74 75 75 76 76 76 kotlin.logging Chapter 27: Loops in Kotlin Remarks Examples Repeat an action x times Looping over iterables While Loops Break and continue Iterating over a Map in kotlin Recursion Functional constructs for iteration Chapter 28: Null Safety Examples Nullable and Non-Nullable types Safe call operator Idiom: calling multiple methods on the same, null-checked object Smart casts Eliminate nulls from an Iterable and array Null Coalescing / Elvis Operator Assertion Elvis Operator (?:) Chapter 29: Ranges Introduction Examples Integral Type Ranges downTo() function step() function until function Chapter 30: RecyclerView in Kotlin Introduction Examples Main class and Adapter 76 77 77 77 77 77 78 78 78 79 79 80 80 80 80 80 81 81 81 82 82 83 83 83 83 83 83 83 84 84 84 84 Chapter 31: Reflection Introduction Remarks Examples Referencing a class Referencing a function Inter-operating with Java reflection Getting values of all properties of a class Setting values of all properties of a class Chapter 32: Regex Examples Idioms for Regex Matching in When Expression Using immutable locals: Using anonymous temporaries: Using the visitor pattern: Introduction to regular expressions in Kotlin The RegEx class Null safety with regular expressions Raw strings in regex patterns find(input: CharSequence, startIndex: Int): MatchResult? findAll(input: CharSequence, startIndex: Int): Sequence matchEntire(input: CharSequence): MatchResult? matches(input: CharSequence): Boolean containsMatchIn(input: CharSequence): Boolean split(input: CharSequence, limit: Int): List replace(input: CharSequence, replacement: String): String Chapter 33: Singleton objects Introduction Examples Use as repalcement of static methods/fields of java Use as a singleton 86 86 86 86 86 86 86 87 87 90 90 90 90 90 90 91 91 91 92 92 92 93 93 93 93 94 95 95 95 95 95 Chapter 34: Strings Examples Elements of String String Literals String Templates String Equality Chapter 35: Type aliases Introduction Syntax Remarks Examples Function type Generic type Chapter 36: Type-Safe Builders Remarks A typical structure of a type-safe builder Type-safe builders in Kotlin libraries Examples Type-safe tree structure builder Chapter 37: Vararg Parameters in Functions Syntax Examples Basics: Using the vararg keyword Spread Operator: Passing arrays into vararg functions Chapter 38: Visibility Modifiers Introduction Syntax Examples Code Sample Credits 97 97 97 97 98 98 100 100 100 100 100 100 100 101 101 101 101 101 101 103 103 103 103 103 105 105 105 105 105 106 About You can share this PDF with anyone you feel could benefit from it, downloaded the latest version from: kotlin It is an unofficial and free Kotlin ebook created for educational purposes. All the content is extracted from Stack Overflow Documentation, which is written by many hardworking individuals at Stack Overflow. It is neither affiliated with Stack Overflow nor official Kotlin. The content is released under Creative Commons BY-SA, and the list of contributors to each chapter are provided in the credits section at the end of this book. Images may be copyright of their respective owners unless otherwise specified. All trademarks and registered trademarks are the property of their respective company owners. Use the content presented in this book at your own risk; it is not guaranteed to be correct nor accurate, please send your feedback and corrections to info@zzzprojects.com https://riptutorial.com/ 1 Chapter 1: Getting started with Kotlin Remarks Kotlin is a statically-typed object-oriented programming language developed by JetBrains primarily targeting the JVM. Kotlin is developed with the goals of being quick to compile, backwards- compatible, very type safe, and 100% interoperable with Java. Kotlin is also developed with the goal of providing many of the features wanted by Java developers. Kotlin's standard compiler allows it to be compiled both into Java bytecode for the JVM and into JavaScript. Compiling Kotlin Kotlin has a standard IDE plugin for Eclipse and IntelliJ. Kotlin can also be compiled using Maven, using Ant, and using Gradle, or through the command line. It is worth noting in $ kotlinc Main.kt will output a java class file, in this case MainKt.class (Note the Kt appended to the class name). However if one was to run the class file using $ java MainKt java will throw the following exception: Exception in thread "main" java.lang.NoClassDefFoundError: kotlin/jvm/internal/Intrinsics at MainKt.main(Main.kt) Caused by: java.lang.ClassNotFoundException: kotlin.jvm.internal.Intrinsics at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ... 1 more In order to run the resulting class file using Java, one must include the Kotlin runt-time jar file to the current class path. java -cp .:/path/to/kotlin/runtime/jar/kotlin-runtime.jar MainKt Versions Version Release Date 1.0.0 2016-02-15 1.0.1 2016-03-16 1.0.2 2016-05-13 1.0.3 2016-06-30 1.0.4 2016-09-22 https://riptutorial.com/ 2 Version Release Date 1.0.5 2016-11-08 1.0.6 2016-12-27 1.1.0 2017-03-01 1.1.1 2017-03-14 1.1.2 2017-04-25 1.1.3 2017-06-23 Examples Hello World All Kotlin programs start at the main function. Here is an example of a simple Kotlin "Hello World" program: package my.program fun main(args: Array) { println("Hello, world!") } Place the above code into a file named Main.kt (this filename is entirely arbitrary) When targeting the JVM, the function will be compiled as a static method in a class with a name derived from the filename. In the above example, the main class to run would be my.program.MainKt . To change the name of the class that contains top-level functions for a particular file, place the following annotation at the top of the file above the package statement: @file:JvmName("MyApp") In this example, the main class to run would now be my.program.MyApp. See also: • • Package level functions including @JvmName annotation. Annotation use-site targets Hello World using an Object Declaration You can alternatively use an Object Declaration that contains the main function for a Kotlin program. https://riptutorial.com/ 3 package my.program object App { @JvmStatic fun main(args: Array) { println("Hello World") } } The class name that you will run is the name of your object, in this case is my.program.App. The advantage to this method over a top-level function is that the class name to run is more self- evident, and any other functions you add are scoped into the class App. You then also have a singleton instance of App to store state and do other work. See also: • Static Methods including the @JvmStatic annotation Hello World using a Companion Object Similar to using an Object Declaration, you can define the main function of a Kotlin program using a Companion Object of a class. package my.program class App { companion object { @JvmStatic fun main(args: Array) { println("Hello World") } } } The class name that you will run is the name of your class, in this case is my.program.App. The advantage to this method over a top-level function is that the class name to run is more self- evident, and any other functions you add are scoped into the class App. This is similar to the Object Declaration example, other than you are in control of instantiating any classes to do further work. A slight variation that instantiates the class to do the actual "hello": class App { companion object { @JvmStatic fun main(args: Array) { App().run() } } fun run() { println("Hello World") } } https://riptutorial.com/ 4 See also: • Static Methods including the @JvmStatic annotation Main methods using varargs All of these main method styles can also be used with varargs: package my.program fun main(vararg args: String) { println("Hello, world!") } Compile and Run Kotlin Code in Command Line As java provide two different commands to compile and run Java code. Same as Kotlin also provide you different commands. javac to compile java files. java to run java files. Same as kotlinc to compile kotlin files kotlin to run kotlin files. Reading input from Command Line The arguments passed from the console can be received in the Kotlin program and it can be used as an input. You can pass N (1 2 3 and so on) numbers of arguments from the command prompt. A simple example of a command-line argument in Kotlin. fun main(args: Array) { println("Enter Two number") var (a, b) = readLine()!!.split(' ') // !! this operator use for NPE(NullPointerException). println("Max number is : ${maxNum(a.toInt(), b.toInt())}") } fun maxNum(a: Int, b: Int): Int { var max = if (a > b) { println("The value of a is $a"); a } else { println("The value of b is $b") b } return max; } https://riptutorial.com/ 5 Here, Enter two number from the command line to find the maximum number. Output : Enter Two number 71 89 // Enter two number from command line The value of b is 89 Max number is: 89 For !! Operator Please check Null Safety. Note: Above example compile and run on Intellij. Read Getting started with Kotlin online: https://riptutorial.com/kotlin/topic/490/getting-started-with- kotlin https://riptutorial.com/ 6 Chapter 2: Annotations Examples Declaring an annotation Annotations are means of attaching metadata to code. To declare an annotation, put the annotation modifier in front of a class: annotation class Strippable Annotations can have meta-anotations: @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION, AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.EXPRESSION) annotation class Strippable Annotations, like other classes, can have constructors: annotation class Strippable(val importanceValue: Int) But unlike other classes, is limited to the following types: • • • • • • types that correspond to Java primitive types (Int, Long etc.); strings classes ( Foo:: class) enums other annotations arrays of the types listed above Meta-annotations When declaring an annotation, meta-info can be included using the following meta-annotations: • • • • @Target: specifies the possible kinds of elements which can be annotated with the annotation (classes, functions, properties, expressions etc.) @Retention specifies whether the annotation is stored in the compiled class files and whether it's visible through reflection at runtime (by default, both are true.) @Repeatable allows using the same annotation on a single element multiple times. @MustBeDocumented specifies that the annotation is part of the public API and should be included in the class or method signature shown in the generated API documentation. Example: https://riptutorial.com/ 7 @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION, AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.EXPRESSION) @Retention(AnnotationRetention.SOURCE) @MustBeDocumented annotation class Fancy Read Annotations online: https://riptutorial.com/kotlin/topic/4074/annotations https://riptutorial.com/ 8 Chapter 3: Arrays Examples Generic Arrays Generic arrays in Kotlin are represented by Array. To create an empty array, use emptyArray() factory function: val empty = emptyArray() To create an array with given size and initial values, use the constructor: var strings = Array(size = 5, init = { index -> "Item #$index" }) print(Arrays.toString(a)) // prints "[Item #0, Item #1, Item #2, Item #3, Item #4]" print(a.size) // prints 5 Arrays have get(index: Int): T and set(index: Int, value: T) functions: strings.set(2, "ChangedItem") print(strings.get(2)) // prints "ChangedItem" // You can use subscription as well: strings[2] = "ChangedItem" print(strings[2]) // prints "ChangedItem" Arrays of Primitives These types do not inherit from Array to avoid boxing, however, they have the same attributes and methods. Kotlin type Factory function JVM type BooleanArray booleanArrayOf(true, false) boolean[] ByteArray byteArrayOf(1, 2, 3) byte[] CharArray charArrayOf('a', 'b', 'c') char[] DoubleArray doubleArrayOf(1.2, 5.0) double[] FloatArray floatArrayOf(1.2, 5.0) float[] IntArray intArrayOf(1, 2, 3) int[] LongArray longArrayOf(1, 2, 3) long[] ShortArray shortArrayOf(1, 2, 3) short[] https://riptutorial.com/ 9 Extensions average() is defined for Byte, Int, Long, Short, Double, Float and always returns Double: val doubles = doubleArrayOf(1.5, 3.0) print(doubles.average()) // prints 2.25 val ints = intArrayOf(1, 4) println(ints.average()) // prints 2.5 component1(), component2(), ... component5() return an item of the array getOrNull(index: Int) returns null if index is out of bounds, otherwise an item of the array first(), last() toHashSet() returns a HashSet of all elements sortedArray(), sortedArrayDescending() creates and returns a new array with sorted elements of current sort(), sortDescending sort the array in-place min(), max() Iterate Array You can print the array elements using the loop same as the Java enhanced loop, but you need to change keyword from : to in. val asc = Array(5, { i -> (i * i).toString() }) for(s : String in asc){ println(s); } You can also change data type in for loop. val asc = Array(5, { i -> (i * i).toString() }) for(s in asc){ println(s); } Create an array val a = arrayOf(1, 2, 3) // creates an Array of size 3 containing [1, 2, 3]. Create an array using a closure val a = Array(3) { i -> i * 2 } // creates an Array of size 3 containing [0, 2, 4] https://riptutorial.com/ 10 Create an uninitialized array val a = arrayOfNulls(3) // creates an Array of [null, null, null] The returned array will always have a nullable type. Arrays of non-nullable items can't be created uninitialized. Read Arrays online: https://riptutorial.com/kotlin/topic/5722/arrays https://riptutorial.com/ 11 Chapter 4: Basic Lambdas Syntax • • • • • • • • • • Explicit parameters: { parameterName: ParameterType, otherParameterName: OtherParameterType -> anExpression() } Inferred parameters: val addition: (Int, Int) -> Int = { a, b -> a + b } Single parameter it shorthand val square: (Int) -> Int = { it*it } Signature: () -> ResultType (InputType) -> ResultType (InputType1, InputType2) -> ResultType Remarks Input type parameters can be left out when they can be left out when they can be inferred from the context. For example say you have a function on a class that takes a function: data class User(val fistName: String, val lastName: String) { fun username(userNameGenerator: (String, String) -> String) = userNameGenerator(firstName, secondName) } You can use this function by passing a lambda, and since the parameters are already specified in the function signature there's no need to re-declare them in the lambda expression: val user = User("foo", "bar") println(user.userName { firstName, secondName -> "${firstName.toUppercase}"_"${secondName.toUppercase}" }) // prints FOO_BAR This also applies when you are assigning a lambda to a variable: //valid: val addition: (Int, Int) = { a, b -> a + b } //valid: val addition = { a: Int, b: Int -> a + b } https://riptutorial.com/ 12 //error (type inference failure): val addition = { a, b -> a + b } When the lambda takes one parameter, and the type can be inferred from the context, you can refer to the parameter by it. listOf(1,2,3).map { it * 2 } // [2,4,6] Examples Lambda as parameter to filter function val allowedUsers = users.filter { it.age > MINIMUM_AGE } Lambda passed as a variable val isOfAllowedAge = { user: User -> user.age > MINIMUM_AGE } val allowedUsers = users.filter(isOfAllowedAge) Lambda for benchmarking a function call General-purpose stopwatch for timing how long a function takes to run: object Benchmark { fun realtime(body: () -> Unit): Duration { val start = Instant.now() try { body() } finally { val end = Instant.now() return Duration.between(start, end) } } } Usage: val time = Benchmark.realtime({ // some long-running code goes here ... }) println("Executed the code in $time") Read Basic Lambdas online: https://riptutorial.com/kotlin/topic/5878/basic-lambdas https://riptutorial.com/ 13 Chapter 5: Basics of Kotlin Introduction This topic covers the basics of Kotlin for beginners. Remarks 1. 2. 3. 4. 5. Kotlin file has an extension .kt. All classes in Kotlin have a common superclass Any, that is a default super for a class with no supertypes declared(similar to Object in Java). Variables can be declared as val(immutable- assign once) or var(mutables- value can be changed) Semicolon is not needed at end of statement. If a function does not return any useful value, its return type is Unit.It is also optional. 6.Referential equality is checked by the === operation. a === b evaluates to true if and only if a and b point to the same object. Examples Basic examples 1.The Unit return type declaration is optional for functions. The following codes are equivalent. fun printHello(name: String?): Unit { if (name != null) println("Hello ${name}") } fun printHello(name: String?) { ... } 2.Single-Expression functions:When a function returns a single expression, the curly braces can be omitted and the body is specified after = symbol fun double(x: Int): Int = x * 2 Explicitly declaring the return type is optional when this can be inferred by the compiler fun double(x: Int) = x * 2 3.String interpolation: Using string values is easy. In java: int num=10 https://riptutorial.com/ 14 String s = "i =" + i; In Kotlin val num = 10 val s = "i = $num" 4.In Kotlin, the type system distinguishes between references that can hold null (nullable references) and those that can not (non-null references). For example, a regular variable of type String can not hold null: var a: String = "abc" a = null // compilation error To allow nulls, we can declare a variable as nullable string, written String?: var b: String? = "abc" b = null // ok 5.In Kotlin,== actually checks for equality of values.By convention, an expression like a == b is translated to a?.equals(b) ?: (b === null) Read Basics of Kotlin online: https://riptutorial.com/kotlin/topic/10648/basics-of-kotlin https://riptutorial.com/ 15 Chapter 6: Class Delegation Introduction A Kotlin class may implement an interface by delegating its methods and properties to another object that implements that interface. This provides a way to compose behavior using association rather than inheritance. Examples Delegate a method to another class interface Foo { fun example() } class Bar { fun example() { println("Hello, world!") } } class Baz(b : Bar) : Foo by b Baz(Bar()).example() The example prints Hello, world! Read Class Delegation online: https://riptutorial.com/kotlin/topic/10575/class-delegation https://riptutorial.com/ 16 Chapter 7: Class Inheritance Introduction Any object-oriented programming language has some form of class inheritance. Let me revise: Imagine you had to program a bunch of fruit: Apples, Oranges and Pears. They all differ in size, shape and color, that's why we have different classes. But let's say their differences don't matter for a second and you just want a Fruit, no matter which exactly? What return type would getFruit() have? The answer is class Fruit. We create a new class and make all fruits inherit from it! Syntax • • • • open {Base Class} class {Derived Class} : {Base Class}({Init Arguments}) override {Function Definition} {DC-Object} is {Base Class} == true Parameters Parameter Details Base Class Class that is inherited from Derived Class Class that inherits from Base Class Init Arguments Arguments passed to constructor of Base Class Function Definition Function in Derived Class that has different code than the same in the Base Class DC-Object ”Derived Class-Object“ Object that has the type of the Derived Class Examples Basics: the 'open' keyword In Kotlin, classes are final by default which means they cannot be inherited from. To allow inheritance on a class, use the open keyword. https://riptutorial.com/ 17 open class Thing { // I can now be extended! } Note: abstract classes, sealed classes and interfaces will be open by default. Inheriting fields from a class Defining the base class: open class BaseClass { val x = 10 } Defining the derived class: class DerivedClass: BaseClass() { fun foo() { println("x is equal to " + x) } } Using the subclass: fun main(args: Array) { val derivedClass = DerivedClass() derivedClass.foo() // prints: 'x is equal to 10' } Inheriting methods from a class Defining the base class: open class Person { fun jump() { println("Jumping...") } } Defining the derived class: class Ninja: Person() { fun sneak() { println("Sneaking around...") } } The Ninja has access to all of the methods in Person https://riptutorial.com/ 18 fun main(args: Array) { val ninja = Ninja() ninja.jump() // prints: 'Jumping...' ninja.sneak() // prints: 'Sneaking around...' } Overriding properties and methods Overriding properties (both read-only and mutable): abstract class Car { abstract val name: String; open var speed: Int = 0; } class BrokenCar(override val name: String) : Car() { override var speed: Int get() = 0 set(value) { throw UnsupportedOperationException("The car is bloken") } } fun main(args: Array) { val car: Car = BrokenCar("Lada") car.speed = 10 } Overriding methods: interface Ship { fun sail() fun sink() } object Titanic : Ship { var canSail = true override fun sail() { sink() } override fun sink() { canSail = false } } Read Class Inheritance online: https://riptutorial.com/kotlin/topic/5622/class-inheritance https://riptutorial.com/ 19 Chapter 8: Collections Introduction Unlike many languages, Kotlin distinguishes between mutable and immutable collections (lists, sets, maps, etc). Precise control over exactly when collections can be edited is useful for eliminating bugs, and for designing good APIs. Syntax • • • listOf, mapOf and setOf returns read-only objects that you cannot add or remove items. If you want to add or remove items you have to use arrayListOf, hashMapOf, hashSetOf, linkedMapOf (LinkedHashMap), linkedSetOf (LinkedHashSet), mutableListOf (The Kotlin MultableList collection), mutableMapOf (The Kotlin MultableMap collection), mutableSetOf (The Kotlin MultableSet collection), sortedMapOf or sortedSetOf Each collection has methods like first(), last(), get() and lambda functions like filter, map, join, reduce and many others. Examples Using list // Create a new read-only List val list = listOf("Item 1", "Item 2", "Item 3") println(list) // prints "[Item 1, Item 2, Item 3]" Using map // Create a new read-only Map val map = mapOf(Pair(1, "Item 1"), Pair(2, "Item 2"), Pair(3, "Item 3")) println(map) // prints "{1=Item 1, 2=Item 2, 3=Item 3}" Using set // Create a new read-only Set val set = setOf(1, 3, 5) println(set) // prints "[1, 3, 5]" Read Collections online: https://riptutorial.com/kotlin/topic/8846/collections https://riptutorial.com/ 20 Chapter 9: Conditional Statements Remarks In contrast to Java's switch, the when statement has no fall-through behavior. This means, that if a branch is matched, the control flow returns after its execution and no break statement is required. If you want to combine the bahaviors for multiple arguments, you can write multiple arguments separated by commas: when (x) { "foo", "bar" -> println("either foo or bar") else -> println("didn't match anything") } Examples Standard if-statement val str = "Hello!" if (str.length == 0) { print("The string is empty!") } else if (str.length > 5) { print("The string is short!") } else { print("The string is long!") } The else-branches are optional in normal if-statements. If-statement as an expression If-statements can be expressions: val str = if (condition) "Condition met!" else "Condition not met!" Note that the else-branch is not optional if the if-statement is used as an expression. This can also been done with a multi-line variant with curly brackets and multiple else if statements. val str = if (condition1){ "Condition1 met!" } else if (condition2) { "Condition2 met!" } else { "Conditions not met!" } https://riptutorial.com/ 21 TIP: Kotlin can infer the type of the variable for you but if you want to be sure of the type just annotate it on the variable like: val str: String = this will enforce the type and will make it easier to read. When-statement instead of if-else-if chains The when-statement is an alternative to an if-statement with multiple else-if-branches: when { str.length == 0 -> print("The string is empty!") str.length > 5 -> print("The string is short!") else -> print("The string is long!") } Same code written using an if-else-if chain: if (str.length == 0) { print("The string is empty!") } else if (str.length > 5) { print("The string is short!") } else { print("The string is long!") } Just like with the if-statement, the else-branch is optional, and you can add as many or as few branches as you like. You can also have multiline-branches: when { condition -> { doSomething() doSomeMore() } else -> doSomethingElse() } When-statement argument matching When given an argument, the when-statement matches the argument against the branches in sequence. The matching is done using the == operator which performs null checks and compares the operands using the equals function. The first matching one will be executed. when (x) { "English" -> print("How are you?") "German" -> print("Wie geht es dir?") else -> print("I don't know that language yet :(") } The when statement also knows some more advanced matching options: val names = listOf("John", "Sarah", "Tim", "Maggie") when (x) { in names -> print("I know that name!") https://riptutorial.com/ 22 !in 1..10 -> print("Argument was not in the range from 1 to 10") is String -> print(x.length) // Due to smart casting, you can use String-functions here } When-statement as expression Like if, when can also be used as an expression: val greeting = when (x) { "English" -> "How are you?" "German" -> "Wie geht es dir?" else -> "I don't know that language yet :(" } print(greeting) To be used as an expression, the when-statement must be exhaustive, i.e. either have an else branch or cover all possibilities with the branches in another way. When-statement with enums when can be used to match enum values: enum class Day { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday } fun doOnDay(day: Day) { when(day) { Day.Sunday -> // Do something Day.Monday, Day.Tuesday -> // Do other thing Day.Wednesday -> // ... Day.Thursday -> // ... Day.Friday -> // ... Day.Saturday -> // ... } } As you can see in second case line (Monday and Tuedsay) it is also possible to combine two or more enum values. If your cases are not exhaustive the compile will show an error. You can use else to handle default cases: fun doOnDay(day: Day) { when(day) { Day.Monday -> // Work Day.Tuesday -> // Work hard Day.Wednesday -> // ... https://riptutorial.com/ 23 Day.Thursday -> // Day.Friday -> // else -> // Party on weekend } } Though the same can be done using if-then-else construct, when takes care of missing enum values and makes it more natural. Check here for more information about kotlin enum Read Conditional Statements online: https://riptutorial.com/kotlin/topic/2685/conditional-statements https://riptutorial.com/ 24 Chapter 10: Configuring Kotlin build Examples Gradle configuration kotlin-gradle-plugin is used to compile Kotlin code with Gradle. Basically, its version should correspond to the Kotlin version you want to use. E.g. if you want to use Kotlin 1.0.3, then you need to aplly kotlin-gradle-plugin version 1.0.3 too. It's a good idea to externalize this version in gradle.properties or in ExtraPropertiesExtension: buildscript { ext.kotlin_version = '1.0.3' repositories { mavenCentral() } dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } Then you need to apply this plugin to your project. The way you do this differs when targeting different platforms: Targeting JVM apply plugin: 'kotlin' Targeting Android apply plugin: 'kotlin-android' Targeting JS apply plugin: 'kotlin2js' These are the default paths: • • • • kotlin sources: src/main/kotlin java sources: src/main/java kotlin tests: src/test/kotlin java tests: src/test/java https://riptutorial.com/ 25 • • runtime resources: src/main/resources test resources: src/test/resources You may need to configure SourceSets if you're using custom project layout. Finally, you'll need to add Kotlin standard library dependency to your project: dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" } If you want to use Kotlin Reflection you'll also need to add compile "org.jetbrains.kotlin:kotlin- reflect:$kotlin_version" Using Android Studio Android Studio can configure Kotlin automatically in an Android project. Install the plugin To install the Kotlin plugin, go to File > Settings > Editor > Plugins > Install JetBrains Plugin... > Kotlin > Install, then restart Android Studio when prompted. Configure a project Create an Android Studio project as normal, then press Ctrl + Shift + A. In the search box, type "Configure Kotlin in Project" and press Enter. Android Studio will alter your Gradle files to add all the necessary dependencies. Converting Java To convert your Java files to Kotlin files, press Ctrl + Shift + A and find "Convert Java File to Kotlin File". This will change the current file's extension to .kt and convert the code to Kotlin. https://riptutorial.com/ 26 Migrating from Gradle using Groovy script to Kotlin script Steps: • • • • clone the gradle-script-kotlin project copy/paste from the cloned project to your project: ○ ○ ○ ○ build.gradle.kts gradlew gradlew.bat settings.gradle update the content of the build.gradle.kts based on your needs, you can use as inspiration the scripts in the project just cloned or in one of its samples now open Intellij and open your project, in the explorer window, it should be recognized as a Gradle project, if not, expand it first. • after opening, let Intellij works, open build.gradle.kts and check if there are any error. If the https://riptutorial.com/ 27 highlighting is not working and/or is everything marked red, then close and reopen Intellij • open the Gradle window and refresh it If you are on Windows, you may encounter this bug, download the full Gradle 3.3 distribution and use that instead the one provided. Related. OSX and Ubuntu work out of the box. Small bonus, if you want to avoid all the hassle of publicing on Maven and similar, use Jitpack, the lines to add are almost identical compared to Groovy. You can take inspiration from this project of mine. Read Configuring Kotlin build online: https://riptutorial.com/kotlin/topic/2501/configuring-kotlin-build https://riptutorial.com/ 28 Chapter 11: coroutines Introduction Examples of Kotlin's experimental(yet) implementation of coroutines Examples Simple coroutine which delay's 1 second but not blocks (from official doc) fun main(args: Array) { launch(CommonPool) { // create new coroutine in common thread pool delay(1000L) // non-blocking delay for 1 second (default time unit is ms) println("World!") // print after delay } println("Hello,") // main function continues while coroutine is delayed Thread.sleep(2000L) // block main thread for 2 seconds to keep JVM alive } result Hello, World! Read coroutines online: https://riptutorial.com/kotlin/topic/10936/coroutines https://riptutorial.com/ 29 Chapter 12: Delegated properties Introduction Kotlin can delegate the implementation of a property to a handler object. Some standard handlers are included, such as lazy initialization or observable properties. Custom handlers can also be created. Examples Lazy initialization val foo : Int by lazy { 1 + 1 } println(foo) The example prints 2. Observable properties var foo : Int by Delegates.observable("1") { property, oldValue, newValue -> println("${property.name} was changed from $oldValue to $newValue") } foo = 2 The example prints foo was changed from 1 to 2 Map-backed properties val map = mapOf("foo" to 1) val foo : String by map println(foo) The example prints 1 Custom delegation class MyDelegate { operator fun getValue(owner: Any?, property: KProperty<*>): String { return "Delegated value" } } val foo : String by MyDelegate() println(foo) The example prints Delegated value https://riptutorial.com/ 30 Delegate Can be used as a layer to reduce boilerplate Consider Kotlin's Null Type system and WeakReference. So let's say we have to save some sort of reference and we wanted to avoid memory leaks, here is where WeakReference comes in. take for example this: class MyMemoryExpensiveClass { companion object { var reference: WeakReference? = null fun doWithReference(block: (MyMemoryExpensiveClass) -> Unit) { reference?.let { it.get()?.let(block) } } } init { reference = WeakReference(this) } } Now this is just with one WeakReference. To Reduce this boilerplate, we can use a custom property delegate to help us like so: class WeakReferenceDelegate(initialValue: T? = null) : ReadWriteProperty { var reference = WeakReference(initialValue) private set override fun getValue(thisRef: Any, property: KProperty<*>): T? = reference.get() override fun setValue(thisRef: Any, property: KProperty<*>, value: T?) { reference = WeakReference(value) } } So Now we can use variables that are wrapped with WeakReference just like normal nullable variables ! class MyMemoryExpensiveClass { companion object { var reference: MyMemoryExpensiveClass? by WeakReferenceDelegate() fun doWithReference(block: (MyMemoryExpensiveClass) -> Unit) { reference?.let(block) } } init { reference = this } https://riptutorial.com/ 31 } Read Delegated properties online: https://riptutorial.com/kotlin/topic/10571/delegated-properties https://riptutorial.com/ 32 Chapter 13: DSL Building Introduction Focus on the syntax details to design internal DSLs in Kotlin. Examples Infix approach to build DSL If you have: infix fun T?.shouldBe(expected: T?) = assertEquals(expected, this) you can write the following DSL-like code in your tests: @Test fun test() { 100.plusOne() shouldBe 101 } Overriding invoke method to build DSL If you have: class MyExample(val i: Int) { operator fun invoke(block: MyExample.() -> R) = block() fun Int.bigger() = this > i } you can write the following DSL-like code in your production code: fun main2(args: Array) { val ex = MyExample(233) ex { // bigger is defined in the context of `ex` // you can only call this method inside this context if (777.bigger()) kotlin.io.println("why") } } Using operators with lambdas If you have: val r = Random(233) infix inline operator fun Int.rem(block: () -> Unit) { https://riptutorial.com/ 33 if (r.nextInt(100) < this) block() } You can write the following DSL-like code: 20 % { println("The possibility you see this message is 20%") } Using extensions with lambdas If you have: operator fun String.invoke(block: () -> R) = { try { block.invoke() } catch (e: AssertException) { System.err.println("$this\n${e.message}") } } You can write the following DSL-like code: "it should return 2" { parse("1 + 1").buildAST().evaluate() shouldBe 2 } If you feel confused with shouldBe above, see the example Infix approach to build DSL. Read DSL Building online: https://riptutorial.com/kotlin/topic/10042/dsl-building https://riptutorial.com/ 34 Chapter 14: Enum Remarks Just like in Java, enum classes in Kotlin have synthetic methods allowing to list the defined enum constants and to get an enum constant by its name. The signatures of these methods are as follows (assuming the name of the enum class is EnumClass): EnumClass.valueOf(value: String): EnumClass EnumClass.values(): Array The valueOf() method throws an IllegalArgumentException if the specified name does not match any of the enum constants defined in the class. Every enum constant has properties to obtain its name and position in the enum class declaration: val name: String val ordinal: Int The enum constants also implement the Comparable interface, with the natural order being the order in which they are defined in the enum class. Examples Initialization Enum classes as any other classes can have a constructor and be initialized enum class Color(val rgb: Int) { RED(0xFF0000), GREEN(0x00FF00), BLUE(0x0000FF) } Functions and Properties in enums Enum classes can also declare members (i.e. properties and functions). A semicolon (;) must be placed between the last enum object and the first member declaration. If a member is abstract, the enum objects must implement it. enum class Color { RED { override val rgb: Int = 0xFF0000 }, GREEN { override val rgb: Int = 0x00FF00 https://riptutorial.com/ 35 }, BLUE { override val rgb: Int = 0x0000FF } ; abstract val rgb: Int fun colorString() = "#%06X".format(0xFFFFFF and rgb) } Simple enum enum class Color { RED, GREEN, BLUE } Each enum constant is an object. Enum constants are separated with commas. Mutability Enums can be mutable, this is another way to obtain a singleton behavior: enum class Planet(var population: Int = 0) { EARTH(7 * 100000000), MARS(); override fun toString() = "$name[population=$population]" } println(Planet.MARS) // MARS[population=0] Planet.MARS.population = 3 println(Planet.MARS) // MARS[population=3] Read Enum online: https://riptutorial.com/kotlin/topic/2286/enum https://riptutorial.com/ 36 Chapter 15: Exceptions Examples Catching exception with try-catch-finally Catching exceptions in Kotlin looks very similar to Java try { doSomething() } catch(e: MyException) { handle(e) } finally { cleanup() } You can also catch multiple exceptions try { doSomething() } catch(e: FileSystemException) { handle(e) } catch(e: NetworkException) { handle(e) } catch(e: MemoryException) { handle(e) } finally { cleanup() } try is also an expression and may return value val s: String? = try { getString() } catch (e: Exception) { null } Kotlin doesn't have checked exceptions, so you don't have to catch any exceptions. fun fileToString(file: File) : String { //readAllBytes throws IOException, but we can omit catching it fileContent = Files.readAllBytes(file) return String(fileContent) } Read Exceptions online: https://riptutorial.com/kotlin/topic/7246/exceptions https://riptutorial.com/ 37 Chapter 16: Extension Methods Syntax • • • fun TypeName.extensionName(params, ...) { /* body */ } // Declaration fun TypeNameWithGenerics.extensionName(params, ...) { /* body */ } // Declaration with Generics myObj.extensionName(args, ...) // invocation Remarks Extensions are resolved statically. This means that the extension method to be used is determined by the reference-type of the variable you are accessing; it doesn't matter what the variable's type is at runtime, the same extension method will always be called. This is because declaring an extension method doesn't actually add a member to the receiver type. Examples Top-Level Extensions Top-level extension methods are not contained within a class. fun IntArray.addTo(dest: IntArray) { for (i in 0 .. size - 1) { dest[i] += this[i] } } Above an extension method is defined for the type IntArray. Note that the object for which the extension method is defined (called the receiver) is accessed using the keyword this. This extension can be called like so: val myArray = intArrayOf(1, 2, 3) intArrayOf(4, 5, 6).addTo(myArray) Potential Pitfall: Extensions are Resolved Statically The extension method to be called is determined at compile-time based on the reference-type of the variable being accessed. It doesn't matter what the variable's type is at runtime, the same extension method will always be called. open class Super class Sub : Super() https://riptutorial.com/ 38 fun Super.myExtension() = "Defined for Super" fun Sub.myExtension() = "Defined for Sub" fun callMyExtension(myVar: Super) { println(myVar.myExtension()) } callMyExtension(Sub()) The above example will print "Defined for Super", because the declared type of the variable myVar is Super. Sample extending long to render a human readable string Given any value of type Int or Long to render a human readable string: fun Long.humanReadable(): String { if (this <= 0) return "0" val units = arrayOf("B", "KB", "MB", "GB", "TB", "EB") val digitGroups = (Math.log10(this.toDouble())/Math.log10(1024.0)).toInt(); return DecimalFormat("#,##0.#").format(this/Math.pow(1024.0, digitGroups.toDouble())) + " " + units[digitGroups]; } fun Int.humanReadable(): String { return this.toLong().humanReadable() } Then easily used as: println(1999549L.humanReadable()) println(someInt.humanReadable()) Sample extending Java 7+ Path class A common use case for extension methods is to improve an existing API. Here are examples of adding exist, notExists and deleteRecursively to the Java 7+ Path class: fun Path.exists(): Boolean = Files.exists(this) fun Path.notExists(): Boolean = !this.exists() fun Path.deleteRecursively(): Boolean = this.toFile().deleteRecursively() Which can now be invoked in this example: val dir = Paths.get(dirName) if (dir.exists()) dir.deleteRecursively() Using extension functions to improve readability In Kotlin you could write code like: https://riptutorial.com/ 39 val x: Path = Paths.get("dirName").apply { if (Files.notExists(this)) throw IllegalStateException("The important file does not exist") } But the use of apply is not that clear as to your intent. Sometimes it is clearer to create a similar extension function to in effect rename the action and make it more self-evident. This should not be allowed to get out of hand, but for very common actions such as verification: infix inline fun T.verifiedBy(verifyWith: (T) -> Unit): T { verifyWith(this) return this } infix inline fun T.verifiedWith(verifyWith: T.() -> Unit): T { this.verifyWith() return this } You could now write the code as: val x: Path = Paths.get("dirName") verifiedWith { if (Files.notExists(this)) throw IllegalStateException("The important file does not exist") } Which now let's people know what to expect within the lambda parameter. Note that the type parameter T for verifiedBy is same as T: Any? meaning that even nullable types will be able to use that version of the extension. Although verifiedWith requires non-nullable. Sample extending Java 8 Temporal classes to render an ISO formatted string With this declaration: fun Temporal.toIsoString(): String = DateTimeFormatter.ISO_INSTANT.format(this) You can now simply: val dateAsString = someInstant.toIsoString() Extension functions to Companion Objects (appearance of Static functions) If you want to extend a class as-if you are a static function, for example for class Something add static looking function fromString, this can only work if the class has a companion object and that the extension function has been declared upon the companion object: class Something { companion object {} } https://riptutorial.com/ 40 class SomethingElse { } fun Something.Companion.fromString(s: String): Something = ... fun SomethingElse.fromString(s: String): SomethingElse = ... fun main(args: Array) { Something.fromString("") //valid as extension function declared upon the //companion object SomethingElse().fromString("") //valid, function invoked on instance not //statically SomethingElse.fromString("") //invalid } Lazy extension property workaround Assume you want to create an extension property that is expensive to compute. Thus you would like to cache the computation, by using the lazy property delegate and refer to current instance ( this), but you cannot do it, as explained in the Kotlin issues KT-9686 and KT-13053. However, there is an official workaround provided here. In the example, the extension property is color. It uses an explicit colorCache which can be used with this as no lazy is necessary: class KColor(val value: Int) private val colorCache = mutableMapOf() val KColor.color: Color get() = colorCache.getOrPut(this) { Color(value, true) } Extensions for easier reference View from code You can use extensions for reference View, no more boilerplate after you created the views. Original Idea is by Anko Library Extensions inline fun View.find(id: Int): T = findViewById(id) as T inline fun Activity.find(id: Int): T = findViewById(id) as T inline fun Fragment.find(id: Int): T = view?.findViewById(id) as T inline fun RecyclerView.ViewHolder.find(id: Int): T = itemView?.findViewById(id) as T inline fun View.findOptional(id: Int): T? = findViewById(id) as? T inline fun Activity.findOptional(id: Int): T? = findViewById(id) as? T inline fun Fragment.findOptional(id: Int): T? = view?.findViewById(id) as? T inline fun RecyclerView.ViewHolder.findOptional(id: Int): T? = https://riptutorial.com/ 41 itemView?.findViewById(id) as? T Usage val yourButton by lazy { find