Kotlin Notes For Professionals Book Goalkicker Books download
Kotlin Notes For Professionals Book Goalkicker Books download
Books download
https://ebookbell.com/product/kotlin-notes-for-professionals-
book-goalkicker-books-43246544
https://ebookbell.com/product/kotlin-notes-for-professionals-
goalkickercom-22033514
The Toronto Notes 2012 Comprehensive Medical Reference And Review For
The Medical Council Of Canada Qualifying Exam Part 1 And The United
States Medical Licensing Exam Step 2 28th Ed Klostranec
https://ebookbell.com/product/the-toronto-notes-2012-comprehensive-
medical-reference-and-review-for-the-medical-council-of-canada-
qualifying-exam-part-1-and-the-united-states-medical-licensing-exam-
step-2-28th-ed-klostranec-6855134
https://ebookbell.com/product/kotlin-the-ultimate-guide-1st-edition-
sufyan-bin-uzayr-46887672
https://ebookbell.com/product/kotlin-in-action-second-edition-
meap-v09-chapters-1-to-10-of-16-svetlana-isakova-50703078
Kotlin Essentials Marcin Moskaa
https://ebookbell.com/product/kotlin-essentials-marcin-moskaa-50821696
https://ebookbell.com/product/kotlin-multiplatform-by-tutorials-
second-edition-2nd-edition-carlos-mota-54275474
https://ebookbell.com/product/kotlin-programming-concise-expressive-
and-powerful-theophilus-edet-55274912
https://ebookbell.com/product/kotlin-blueprints-belagali-ashish-
trivedi-hardik-chordiya-akshay-22090866
https://ebookbell.com/product/kotlin-cookbook-a-problemfocused-
approach-1st-edition-ken-kousen-34710648
Kotlin
Kotlin
Notes for Professionals
®
80+ pages
of professional hints and tricks
Disclaimer
GoalKicker.com This is an unocial free book created for educational purposes and is
not aliated with ocial Kotlin® group(s) or company(s).
Free Programming Books All trademarks and registered trademarks are
the property of their respective owners
Contents
About ................................................................................................................................................................................... 1
Chapter 1: Getting started with Kotlin ............................................................................................................... 2
Section 1.1: Hello World ................................................................................................................................................. 2
Section 1.2: Hello World using a Companion Object .................................................................................................. 2
Section 1.3: Hello World using an Object Declaration ................................................................................................ 3
Section 1.4: Main methods using varargs .................................................................................................................... 4
Section 1.5: Compile and Run Kotlin Code in Command Line ................................................................................... 4
Section 1.6: Reading input from Command Line ........................................................................................................ 4
Chapter 2: Basics of Kotlin ....................................................................................................................................... 6
Section 2.1: Basic examples .......................................................................................................................................... 6
Chapter 3: Strings ......................................................................................................................................................... 7
Section 3.1: String Equality ............................................................................................................................................ 7
Section 3.2: String Literals ............................................................................................................................................ 7
Section 3.3: Elements of String ..................................................................................................................................... 8
Section 3.4: String Templates ....................................................................................................................................... 8
Chapter 4: Arrays ......................................................................................................................................................... 9
Section 4.1: Generic Arrays ........................................................................................................................................... 9
Section 4.2: Arrays of Primitives .................................................................................................................................. 9
Section 4.3: Create an array ........................................................................................................................................ 9
Section 4.4: Create an array using a closure ............................................................................................................. 9
Section 4.5: Create an uninitialized array ................................................................................................................... 9
Section 4.6: Extensions ................................................................................................................................................ 10
Section 4.7: Iterate Array ............................................................................................................................................ 10
Chapter 5: Collections .............................................................................................................................................. 11
Section 5.1: Using list ................................................................................................................................................... 11
Section 5.2: Using map ............................................................................................................................................... 11
Section 5.3: Using set .................................................................................................................................................. 11
Chapter 6: Enum .......................................................................................................................................................... 12
Section 6.1: Initialization .............................................................................................................................................. 12
Section 6.2: Functions and Properties in enums ...................................................................................................... 12
Section 6.3: Simple enum ............................................................................................................................................ 12
Section 6.4: Mutability ................................................................................................................................................. 12
Chapter 7: Functions ................................................................................................................................................. 14
Section 7.1: Function References ............................................................................................................................... 14
Section 7.2: Basic Functions ....................................................................................................................................... 15
Section 7.3: Inline Functions ....................................................................................................................................... 16
Section 7.4: Lambda Functions .................................................................................................................................. 16
Section 7.5: Operator functions ................................................................................................................................. 16
Section 7.6: Functions Taking Other Functions ........................................................................................................ 17
Section 7.7: Shorthand Functions .............................................................................................................................. 17
Chapter 8: Vararg Parameters in Functions ................................................................................................ 18
Section 8.1: Basics: Using the vararg keyword ......................................................................................................... 18
Section 8.2: Spread Operator: Passing arrays into vararg functions .................................................................... 18
Chapter 9: Conditional Statements ................................................................................................................... 19
Section 9.1: When-statement argument matching .................................................................................................. 19
Section 9.2: When-statement as expression ............................................................................................................ 19
Section 9.3: Standard if-statement ............................................................................................................................ 19
Section 9.4: If-statement as an expression ............................................................................................................... 19
Section 9.5: When-statement instead of if-else-if chains ....................................................................................... 20
Section 9.6: When-statement with enums ................................................................................................................ 20
Chapter 10: Loops in Kotlin .................................................................................................................................... 22
Section 10.1: Looping over iterables ........................................................................................................................... 22
Section 10.2: Repeat an action x times ...................................................................................................................... 22
Section 10.3: Break and continue ............................................................................................................................... 22
Section 10.4: Iterating over a Map in kotlin ............................................................................................................... 23
Section 10.5: Recursion ............................................................................................................................................... 23
Section 10.6: While Loops ........................................................................................................................................... 23
Section 10.7: Functional constructs for iteration ...................................................................................................... 23
Chapter 11: Ranges ..................................................................................................................................................... 25
Section 11.1: Integral Type Ranges ............................................................................................................................. 25
Section 11.2: downTo() function .................................................................................................................................. 25
Section 11.3: step() function ........................................................................................................................................ 25
Section 11.4: until function ........................................................................................................................................... 25
Chapter 12: Regex ....................................................................................................................................................... 26
Section 12.1: Idioms for Regex Matching in When Expression ................................................................................ 26
Section 12.2: Introduction to regular expressions in Kotlin ..................................................................................... 27
Chapter 13: Basic Lambdas .................................................................................................................................... 30
Section 13.1: Lambda as parameter to filter function .............................................................................................. 30
Section 13.2: Lambda for benchmarking a function call ......................................................................................... 30
Section 13.3: Lambda passed as a variable .............................................................................................................. 30
Chapter 14: Null Safety ........................................................................................................................................... 31
Section 14.1: Smart casts ............................................................................................................................................. 31
Section 14.2: Assertion ................................................................................................................................................. 31
Section 14.3: Eliminate nulls from an Iterable and array ......................................................................................... 31
Section 14.4: Null Coalescing / Elvis Operator .......................................................................................................... 31
Section 14.5: Nullable and Non-Nullable types ......................................................................................................... 32
Section 14.6: Elvis Operator (?:) .................................................................................................................................. 32
Section 14.7: Safe call operator .................................................................................................................................. 32
Chapter 15: Class Delegation ................................................................................................................................ 34
Section 15.1: Delegate a method to another class ................................................................................................... 34
Chapter 16: Class Inheritance ............................................................................................................................... 35
Section 16.1: Basics: the 'open' keyword .................................................................................................................... 35
Section 16.2: Inheriting fields from a class ................................................................................................................ 35
Section 16.3: Inheriting methods from a class .......................................................................................................... 36
Section 16.4: Overriding properties and methods .................................................................................................... 36
Chapter 17: Visibility Modifiers ............................................................................................................................. 38
Section 17.1: Code Sample ........................................................................................................................................... 38
Chapter 18: Generics ................................................................................................................................................. 39
Section 18.1: Declaration-site variance ...................................................................................................................... 39
Section 18.2: Use-site variance ................................................................................................................................... 39
Chapter 19: Interfaces .............................................................................................................................................. 41
Section 19.1: Interface with default implementations ............................................................................................... 41
Section 19.2: Properties in Interfaces ......................................................................................................................... 42
Section 19.3: super keyword ....................................................................................................................................... 42
Section 19.4: Basic Interface ....................................................................................................................................... 42
Section 19.5: Conflicts when Implementing Multiple Interfaces with Default Implementations .......................... 43
Chapter 20: Singleton objects .............................................................................................................................. 44
Section 20.1: Use as replacement of static methods/fields of java ....................................................................... 44
Section 20.2: Use as a singleton ................................................................................................................................ 44
Chapter 21: coroutines ............................................................................................................................................. 45
Section 21.1: Simple coroutine which delay's 1 second but not blocks ................................................................... 45
Chapter 22: Annotations ......................................................................................................................................... 46
Section 22.1: Meta-annotations .................................................................................................................................. 46
Section 22.2: Declaring an annotation ...................................................................................................................... 46
Chapter 23: Type aliases ......................................................................................................................................... 47
Section 23.1: Function type ......................................................................................................................................... 47
Section 23.2: Generic type .......................................................................................................................................... 47
Chapter 24: Type-Safe Builders ......................................................................................................................... 48
Section 24.1: Type-safe tree structure builder .......................................................................................................... 48
Chapter 25: Delegated properties ..................................................................................................................... 49
Section 25.1: Observable properties .......................................................................................................................... 49
Section 25.2: Custom delegation ............................................................................................................................... 49
Section 25.3: Lazy initialization .................................................................................................................................. 49
Section 25.4: Map-backed properties ....................................................................................................................... 49
Section 25.5: Delegate Can be used as a layer to reduce boilerplate .................................................................. 49
Chapter 26: Reflection ............................................................................................................................................. 51
Section 26.1: Referencing a class ............................................................................................................................... 51
Section 26.2: Inter-operating with Java reflection .................................................................................................. 51
Section 26.3: Referencing a function ......................................................................................................................... 51
Section 26.4: Getting values of all properties of a class ......................................................................................... 51
Section 26.5: Setting values of all properties of a class .......................................................................................... 52
Chapter 27: Extension Methods ........................................................................................................................... 54
Section 27.1: Potential Pitfall: Extensions are Resolved Statically .......................................................................... 54
Section 27.2: Top-Level Extensions ........................................................................................................................... 54
Section 27.3: Lazy extension property workaround ................................................................................................ 54
Section 27.4: Sample extending Java 7+ Path class ............................................................................................... 55
Section 27.5: Sample extending long to render a human readable string ........................................................... 55
Section 27.6: Sample extending Java 8 Temporal classes to render an ISO formatted string .......................... 55
Section 27.7: Using extension functions to improve readability ............................................................................. 55
Section 27.8: Extension functions to Companion Objects (appearance of Static functions) .............................. 56
Section 27.9: Extensions for easier reference View from code .............................................................................. 57
Chapter 28: DSL Building ........................................................................................................................................ 58
Section 28.1: Infix approach to build DSL .................................................................................................................. 58
Section 28.2: Using operators with lambdas ............................................................................................................ 58
Section 28.3: Overriding invoke method to build DSL ............................................................................................. 58
Section 28.4: Using extensions with lambdas ........................................................................................................... 58
Chapter 29: Idioms ..................................................................................................................................................... 60
Section 29.1: Serializable and serialVersionUid in Kotlin ......................................................................................... 60
Section 29.2: Delegate to a class without providing it in the public constructor .................................................. 60
Section 29.3: Use let or also to simplify working with nullable objects ................................................................. 61
Section 29.4: Use apply to initialize objects or to achieve method chaining ........................................................ 61
Section 29.5: Fluent methods in Kotlin ...................................................................................................................... 61
Section 29.6: Filtering a list ......................................................................................................................................... 62
Section 29.7: Creating DTOs (POJOs/POCOs) ........................................................................................................ 62
Chapter 30: RecyclerView in Kotlin ................................................................................................................... 63
Section 30.1: Main class and Adapter ........................................................................................................................ 63
Chapter 31: logging in kotlin .................................................................................................................................. 65
Section 31.1: kotlin.logging .......................................................................................................................................... 65
Chapter 32: Exceptions ............................................................................................................................................. 66
Section 32.1: Catching exception with try-catch-finally ........................................................................................... 66
Chapter 33: JUnit ........................................................................................................................................................ 67
Section 33.1: Rules ........................................................................................................................................................ 67
Chapter 34: Kotlin Android Extensions ............................................................................................................ 68
Section 34.1: Using Views ............................................................................................................................................ 68
Section 34.2: Configuration ........................................................................................................................................ 68
Section 34.3: Painful listener for getting notice, when the view is completely drawn now is so simple and
awesome with Kotlin's extension ....................................................................................................................... 69
Section 34.4: Product flavors ..................................................................................................................................... 69
Chapter 35: Kotlin for Java Developers ......................................................................................................... 71
Section 35.1: Declaring Variables ............................................................................................................................... 71
Section 35.2: Quick Facts ............................................................................................................................................ 71
Section 35.3: Equality & Identity ................................................................................................................................. 71
Section 35.4: IF, TRY and others are expressions, not statements ......................................................................... 72
Chapter 36: Java 8 Stream Equivalents ......................................................................................................... 73
Section 36.1: Accumulate names in a List ................................................................................................................. 73
Section 36.2: Collect example #5 - find people of legal age, output formatted string ........................................ 73
Section 36.3: Collect example #6 - group people by age, print age and names together ................................. 73
Section 36.4: Dierent Kinds of Streams #7 - lazily iterate Doubles, map to Int, map to String, print each
................................................................................................................................................................................ 74
Section 36.5: Counting items in a list after filter is applied ..................................................................................... 75
Section 36.6: Convert elements to strings and concatenate them, separated by commas ............................... 75
Section 36.7: Compute sum of salaries of employee .............................................................................................. 75
Section 36.8: Group employees by department ...................................................................................................... 75
Section 36.9: Compute sum of salaries by department .......................................................................................... 75
Section 36.10: Partition students into passing and failing ....................................................................................... 75
Section 36.11: Names of male members ................................................................................................................... 76
Section 36.12: Group names of members in roster by gender ............................................................................... 76
Section 36.13: Filter a list to another list .................................................................................................................... 76
Section 36.14: Finding shortest string a list ............................................................................................................... 76
Section 36.15: Dierent Kinds of Streams #2 - lazily using first item if exists ....................................................... 76
Section 36.16: Dierent Kinds of Streams #3 - iterate a range of Integers .......................................................... 77
Section 36.17: Dierent Kinds of Streams #4 - iterate an array, map the values, calculate the average
................................................................................................................................................................................ 77
Section 36.18: Dierent Kinds of Streams #5 - lazily iterate a list of strings, map the values, convert to Int,
find max ............................................................................................................................................................... 77
Section 36.19: Dierent Kinds of Streams #6 - lazily iterate a stream of Ints, map the values, print results
................................................................................................................................................................................ 77
Section 36.20: How streams work - filter, upper case, then sort a list ................................................................... 78
Section 36.21: Dierent Kinds of Streams #1 - eager using first item if it exists ................................................... 78
Section 36.22: Collect example #7a - Map names, join together with delimiter ................................................... 78
Section 36.23: Collect example #7b - Collect with SummarizingInt ....................................................................... 79
Chapter 37: Kotlin Caveats .................................................................................................................................... 81
Section 37.1: Calling a toString() on a nullable type ................................................................................................ 81
Appendix A: Configuring Kotlin build ................................................................................................................ 82
Section A.1: Gradle configuration ............................................................................................................................... 82
Section A.2: Using Android Studio ............................................................................................................................. 83
Section A.3: Migrating from Gradle using Groovy script to Kotlin script ............................................................... 84
Credits .............................................................................................................................................................................. 86
You may also like ........................................................................................................................................................ 88
About
Please feel free to share this PDF with anyone for free,
latest version of this book can be downloaded from:
https://goalkicker.com/KotlinBook
This Kotlin® Notes for Professionals book is compiled from Stack Overflow
Documentation, the content is written by the beautiful people at Stack Overflow.
Text content is released under Creative Commons BY-SA, see credits at the end
of this book whom contributed to the various chapters. Images may be copyright
of their respective owners unless otherwise specified
This is an unofficial free book created for educational purposes and is not
affiliated with official Kotlin® group(s) or company(s) nor Stack Overflow. All
trademarks and registered trademarks are the property of their respective
company owners
package my.program
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")
See also:
class App {
companion object {
@JvmStatic fun main(args: Array<String>) {
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.
class App {
companion object {
@JvmStatic fun main(args: Array<String>) {
App().run()
}
}
fun run() {
println("Hello World")
}
}
See also:
package my.program
object App {
@JvmStatic fun main(args: Array<String>) {
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:
package my.program
return max;
Here, Enter two number from the command line to find the maximum number. Output:
The value of b is 89
Max number is: 89
'Ah,' cried I, 'you are relenting, you are weeping. Bless you for that.
Dear, dear father, look up, and see with what joy a daughter can
embrace you.'
'My child, my child!' cried he, turning, and throwing himself upon my
bosom. 'A heart of stone could not withstand this! There, there,
there, I forgive you all!'
Fast and fondly did we cling round each other, and sweet were the
sighs that we breathed, and the tears that we shed.
But I suffered too much: the disorder which had some time been
engendering in my frame now burst forth with alarming vehemence,
and I was conveyed raving into a carriage. On our arrival at the
hotel, they sent for a physician, who pronounced me in a violent
fever of a nervous nature. For a fortnight I was not expected to
recover; and I myself felt so convinced of my speedy dissolution,
that I requested the presence of a clergyman. He came; and his
conversations, by composing my mind, contributed in a great degree
to my recovery. At my request, he paid me daily visits. Our subject
was religion,—not those theological controversies which excite so
much irreligious feeling, and teach men to hate each other for the
love of God; but those plain and simple truths which convince
without confounding, and which avoid the bigotry that would
worship error, because it is hereditary; and the fanaticism that would
lay rash hands on the holy temple, because some of its smaller
pillars appear unsound.
Adieu.
LETTER XLVII
He had put Don Quixote (a work which I never read before) into my
hands; and on my returning it to him, with a confession of the
benefit that I derived from it, the conversation naturally ran upon
romances in general. He thus delivered his sentiments.
'In a country where morals are on the decline, novels always fall
several degrees below the standard of national virtue: and the
contrary holds in an opposite state of things. For as these works are
an exaggerated picture of the times, they represent the prevalent
opinions and manners with a gigantic pencil. Thus, since France
became depraved, her novels have become dissolute; and since her
social system arrived at its extreme of vicious refinement, they too
have adopted that last master-stroke of refined vice, which wins the
heart by the chastest aphorisms, and then corrupts it by the most
alluring pictures of villainy. Take Rousseau for instance. What St.
Preux is to Heloise, the book is to the reader. The lover so fascinates
his mistress by his honourable sentiments, that she cannot resist his
criminal advances. The book infatuates the reader, till, in his
admiration of its morality, he loses all recollection of its
licentiousness; for as virtue is more captivating, so vice is less
disgusting when adorned with the Graces. It may be said that an
author ought to portray vice in its seductive colours, for the purpose
of unmasking its arts, and thus warning the young and
inexperienced. But let it be recollected, that though familiarity with
enchanting descriptions of vice may add to prudence, it must
diminish virtue; and that while it teaches the reason to resist, it
entices the passions to yield. It was Rousseau's system, however, to
paint the scenes of a brothel, in order to speak the cant of a
monastery; and thus has he undone many an imitating miss or wife,
who began by listening to the language of love, that she might talk
sentiment, and act virtue; and ended by falling a victim to it,
because her heart had become entangled, her head bewildered, and
her principles depraved.
This having been the day fixed for the trials of Betterton and Grundy,
the prisoners were brought to the bar, and the names of the
prosecutors called. But these did not appear, and of consequence
the culprits were discharged. It is supposed that Betterton, the great
declaimer against bribery and corruption, had tampered with the
postilion and the police, and thus escaped the fate which awaited
him.
Adieu.
LETTER XLVIII
'Pray,' said I, at length, 'what makes you so dull and absent to-day?'
''Tis not what you have done,' answered he; 'but what you will do.'
'When I tell you,' said he, 'that on the possession of this hand
depends my happiness, may I flatter myself with the hope that my
happiness would not contribute to your misery?'
Adieu.
LETTER XLIX
I have just time to tell you, before I leave town, that my fate was
sealed this morning, and that I am a wife.
Honest Jerry Sullivan met me at the door, and shook my hand, and
danced round me in a fury of outrageous joy.
'Well,' cried he, 'often and often I thought your freaks would get you
hanged; but may I be hanged if ever I thought they would get you
married!'
'You see,' said I to Stuart, 'after all your pains to prevent me from
imitating romances, you have made me terminate my adventures
like a true romance—in a wedding. Pray with what moral will you
now conclude the book?'
'I will say,' returned he, 'that virtue—no. That calamity—no. That
fortitude and resignation—oh, no! I will say, then, that Tommy
Horner was a bad boy, and would not get plumcake; and that King
Pepin was a good boy, and rode in a golden coach.'
Adieu.
Transcriber's Note:
The cover of this ebook was created by the transcriber and is hereby placed in
the public domain.
*** END OF THE PROJECT GUTENBERG EBOOK THE HEROINE ***
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside
the United States, check the laws of your country in addition to
the terms of this agreement before downloading, copying,
displaying, performing, distributing or creating derivative works
based on this work or any other Project Gutenberg™ work. The
Foundation makes no representations concerning the copyright
status of any work in any country other than the United States.
1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if
you provide access to or distribute copies of a Project
Gutenberg™ work in a format other than “Plain Vanilla ASCII” or
other format used in the official version posted on the official
Project Gutenberg™ website (www.gutenberg.org), you must,
at no additional cost, fee or expense to the user, provide a copy,
a means of exporting a copy, or a means of obtaining a copy
upon request, of the work in its original “Plain Vanilla ASCII” or
other form. Any alternate format must include the full Project
Gutenberg™ License as specified in paragraph 1.E.1.
• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”
• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.
ebookbell.com