






















































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
KotlinNotesForProfessionals.pdf
Typology: Lecture notes
1 / 94
This page cannot be seen from the preview
Don't miss anything!
Kotlin Notes for Professionals
Notes for Professionals
GoalKicker.com
Section 36.4: Dierent Kinds of Streams #7 - lazily iterate Doubles, map to Int, map to String, print each
Section 36.17: Dierent Kinds of Streams #4 - iterate an array, map the values, calculate the average ................................................................................................................................................................................ 77
Section 36.19: Dierent Kinds of Streams #6 - lazily iterate a stream of Ints, map the values, print results
About
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
The information presented in this book is not guaranteed to be correct nor accurate, use at your own risk
Please send feedback and corrections to web@petercv.com
Chapter 1: Getting started with Kotlin
Version Release Date 1.0.0 2016-02- 1.0.1 2016-03- 1.0.2 2016-05- 1.0.3 2016-06- 1.0.4 2016-09- 1.0.5 2016-11- 1.0.6 2016-12- 1.1.0 2017-03- 1.1.1 2017-03- 1.1.2 2017-04- 1.1.3 2017-06- 1.1.6 2017-11- 1.2.2 2018-01- 1.2.3 2018-03- 1.2.4 2018-04-
Section 1.1: 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
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
Section 1.2: 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.
Section 1.4: 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!") }
Section 1.5: 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.
Section 1.6: 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;
}
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.
Chapter 3: Strings
Section 3.1: String Equality
In Kotlin strings are compared with == operator which check for their structural equality.
val str1 = "Hello, World!" val str2 = "Hello," + " World!" println(str1 == str2) // Prints true
Referential equality is checked with === operator.
val str1 = """ |Hello, World! """.trimMargin()
val str2 = """ #Hello, World! """.trimMargin("#")
val str3 = str
println(str1 == str2) // Prints true println(str1 === str2) // Prints false println(str1 === str3) // Prints true
Section 3.2: String Literals
Kotlin has two types of string literals:
Escaped string Raw string
Escaped string handles special characters by escaping them. Escaping is done with a backslash. The following escape sequences are supported: \t, \b, \n, \r, ', ", \ and $. To encode any other character, use the Unicode escape sequence syntax: \uFF00.
val s = "Hello, world! \n "
Raw string delimited by a triple quote """, contains no escaping and can contain newlines and any other characters
val text = """ for (c in "foo") print(c) """
Leading whitespace can be removed with trimMargin() function.
val text = """ |Tell me and I forget. |Teach me and I remember. |Involve me and I learn. |(Benjamin Franklin) """.trimMargin()
Default margin prefix is pipe character |, this can be set as a parameter to trimMargin; e.g. trimMargin(">").
Section 3.3: Elements of String
Elements of String are characters that can be accessed by the indexing operation string[index].
val str = "Hello, World!" println(str[1]) // Prints e
String elements can be iterated with a for-loop.
for (c in str) { println(c) }
Section 3.4: String Templates
Both escaped strings and raw strings can contain template expressions. Template expression is a piece of code which is evaluated and its result is concatenated into string. It starts with a dollar sign $ and consists of either a variable name:
val i = 10 val s = "i = $i" // evaluates to "i = 10"
Or an arbitrary expression in curly braces:
val s = "abc" val str = "$s.length is ${s.length}" // evaluates to "abc.length is 3"
To include a literal dollar sign in a string, escape it using a backslash:
val str = " $ foo" // evaluates to "$foo"
The exception is raw strings, which do not support escaping. In raw strings you can use the following syntax to represent a dollar sign.
val price = """ ${'$'}9. """
Section 4.6: 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.
val ints = intArrayOf(1, 4) println(ints.average()) // prints 2.
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
sortedArray(), sortedArrayDescending() creates and returns a new array with sorted elements of current
sort(), sortDescending sort the array in-place
min(), max()
Section 4.7: 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); }
Chapter 5: Collections
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.
Section 5.1: Using list
// Create a new read-only List
Section 5.2: Using map
// Create a new read-only Map<Integer, String> 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}"
Section 5.3: Using set
// Create a new read-only Set
println(Planet.MARS) // MARS[population=0] Planet.MARS.population = 3 println(Planet.MARS) // MARS[population=3]
Chapter 7: Functions
Parameter Details Name Name of the function Params Values given to the function with a name and type: Name : Type Type Return type of the function Type Argument Type parameter used in generic programming (not necessarily return type) ArgName Name of value given to the function ArgType Type specifier for ArgName ArgNames List of ArgName separated by commas
Section 7.1: Function References
We can reference a function without actually calling it by prefixing the function's name with ::. This can then be passed to a function which accepts some other function as a parameter.
fun addTwo(x: Int ) = x + 2 listOf(1, 2, 3, 4).map(::addTwo) # => [3, 4, 5, 6]
Functions without a receiver will be converted to (ParamTypeA, ParamTypeB, ...) -> ReturnType where ParamTypeA, ParamTypeB ... are the type of the function parameters and `ReturnType1 is the type of function return value.
fun foo(p0: Foo0, p1: Foo1, p2: Foo2): Bar { //... } println(::foo:: class .java.genericInterfaces[0]) // kotlin.jvm.functions.Function3<Foo0, Foo1, Foo2, Bar> // Human readable type: (Foo0, Foo1, Foo2) -> Bar
Functions with a receiver (be it an extension function or a member function) has a different syntax. You have to add the type name of the receiver before the double colon:
class Foo fun Foo.foo(p0: Foo0, p1: Foo1, p2: Foo2): Bar { //... } val ref = Foo::foo println(ref:: class .java.genericInterfaces[0]) // kotlin.jvm.functions.Function4<Foo, Foo0, Foo1, Foo2, Bar> // Human readable type: (Foo, Foo0, Foo1, Foo2) -> Bar // takes 4 parameters, with receiver as first and actual parameters following, in their order
// this function can't be called like an extension function, though val ref = Foo::foo Foo().ref(Foo0(), Foo1(), Foo2()) // compile error
class Bar { fun bar() } print(Bar::bar) // works on member functions, too.
However, when a function's receiver is an object, the receiver is omitted from parameter list, because these is and only is one instance of such type.