text:
Fundamental Kotlin

Miloš Vasić

First Edition
www.fundamental-kotlin.com

Fundamental Kotlin by Miloš Vasić

Fall 2016: First Edition

Copyright © 2016 Miloš Vasić All rights reserved.

Published by Miloš Vasić, milos.vasic@fundamental-kotlin.com

ISBN: 978-86-920307-0-3

Website: www.fundamental-kotlin.com

# About Fundamental Series

_Fundamental Series_ is a serie of books with intention to bring readers quickly into book's subject and make it possible to relatively easy start working with matter.

_Fundamental Kotlin_ is the first book in _Fundamental Series_. It is available only as the electronic publication.

# About me

I am a software engineer from Belgrade, Serbia. I am passionate about software development and ways to make it better. When I am not on regular projects, I am spending time learning and investigating new technologies. One such technology is Kotlin. It gave me a lot of fun playing with Kotlin features and learning it.

You can also find me here:

\- Linkedin: milos-vasic-53778682

\- Xing: Milos_Vasic4

\- Github: milos85vasic

\- Email: milos.vasic@fundamental-kotlin.com
\- Website: milosvasic.net

# Preface

In the 21st century with fast growth of computer technology developers are facing challenges more than ever. Existing programming languages are sometimes not good enough for them to fulfill mission best possible way.

One such example is Java (but not the only one). Even with Java 8, Java did not bring all modern features that developers in the 21st century expected.

At the moment some new modern technologies are emerging. One of many is Swift, which is very popular. There are some other good examples: Ruby, Go, Haskel, Elixir, Scala as well as many others.

Some programming languages that are not so new to developers like Erlang and Python gained certain popularity because of new trends.

Each language offers some advantages. However, there is still space for new languages to come. That is how Kotlin is born, powerful object-oriented programming language.

## What is this book about?

Fundamental Kotlin is a book focused on Kotlin programming language and it's comparison to Java. This book is focused on language's most important features and aspects. It will not go in too much theory since it's focused on exact examples with notes and code provided. All examples and code for this book are located here:

<http://static.fundamental-kotlin.com/code/Fundamental-Kotlin.zip>

Most of the book and it's organisation are based on official language specifications and docs located on official Kotlin website:

http://www.kotlinlang.org

The reason why I decided to write this book was my strong impression with this language. As I want as much as possible people to try it I decided to write this examples-driven book. If any of you who read notice anything that is not correct in the code examples please report it to me: milos.vasic@fundamental-kotlin.com. I will check and apply the changes in code if needed. Since this is a new technology for me too it is possible that something may come up.

This is the first edition of the book and my plans for the second edition are to update examples, polish it and extend it. Everybody is wellcome to participate so if you have a better example (alternative) than the existing one please email me. I will be more than happy to include your examples.

I hope that you will find this book helpful and practical.

Regards, Miloš.

## Who is this book for?

This book is for developers and for people who are on its way to become developers. It is essential to have at least some basic knowledge of computer programming, especially of Java. Fundamental Kotlin is imagined as guide to Kotlin for developers who spent some time on Java powered projects but it is not mandatory. If you were programming for some time, it should be easy for you to follow this book.

# What is Kotlin?

Kotlin is new programming language running on Java Virtual Machine, Android or browser. It is statically typed language and it can be compiled to JavaScript source code (running on browsers).

Kotlin is:

**Concise** \- drastically reduced code boilerplate

**Safe** \- impossible to get _NullPointerException_

**Versatile** \- it is general-purpose programming language

**Interoperable** \- we can use existing JVM libs and frameworks.

A team at JetBrains (creators of IntelliJ Idea) developed Kotlin, an OSS language with an army of external contributors.

Kotlin's benefits over Java are:

\- It is Java-compatible language

\- It compiles at least as fast as Java

\- It is safer than Java

\- It is more concise than Java

\- Reduces codebase significantly when compared to the same code written in Java

Kotlin is OSS language licensed under Apache 2 OSS License.

## Basic characteristics

Basic Kotlin characteristics are:

1. Running on JVM (Java Virtual Machine) meaning that it is cross-platform compatible

2. Statically typed, the type of a variable is known at compile time

3. Functional:

\- First-class functions: You can store functions as a variables or pass as a parameters to other functions as a parameters

\- Immutability: It is guaranteed that state of an immutable object can't change over time

\- No side effects: Using pure functions that return the same result given the same inputs. Do not modify the state of other objects or interact with the outside world

4. Object-Oriented

5. Free and Open Source

## Where is it used?

As we mentioned, Kotlin is general-purpose programming language. That means that Kotlin can be used for many different needs like:

**Server-side development** , here is the list of some web framework that you can try for web development:

Kara - http://karaframework.com

Wasabi - <https://github.com/hhariri/wasabi>

Yested - http://www.yested.net

Hexagon - <https://github.com/jaguililla/hexagon>

and many others.

**Android mobile development** , you can develop native Android applications from Kotlin.

## Kotlin tools

Kotlin is very similar to Java, and so, as Java, Kotlin has compiler. Let's see now how build process is working in Kotlin.

All source code is stored in _.kt_ files that are organized in packages. This is the same as in Java, the only difference is that Java uses .java extension. Kotlin compiler analyzes source code and generates _.class_ files (as Java does it too). Then, _.class_ files are packaged – the way in which they are package depends on kind of project you are working on.

Like this you can compile and run your code. For example create some _.kt_ source code, then compile it using _kotlinc_ , Kotlin compiler, and finally run it using Java:

$ kotlinc First.kt -include-runtime -d First.jar

$ java -jar First.jar

# How to start?

We will show you how to get Kotlin running and start writing some code. It is very simple, especially if you already were working with Java and IntelliJ Idea.

The previous example was executed using only Java and Kotlin compiler. To get it running and execute commands from example you need to install Java and Kotlin compiler. Latest versions of both may be found on Orcale (Java) and Kotlinlang (Kotlin) websites.

For more serious programming we will need an IDE. In this book (and probably in any future development) you will use IntelliJ Idea, IDE developed by creators of Kotlin, JetBrains Company.

Download and install IntelliJ Idea Community Edition. When it's done, from IDE preferences install support for Kotlin language with all plugins that are coming with it. When done, you are ready to start writing some code.

# Basics

To start writing some code, create new Kotlin project in IntelliJ:

File → New → Project

Then choose:

Kotlin → Kotlin (JVM) → Next

Name the project, set file system location and choose Java version from dropdown list (Project SDK). After you click on Finish button new empty Kotlin project will be created.

Now, create your first package, steps are the same, as you would do in Java. Right click on src folder in project structure tree → New → Package. Give some meaningful name to it like:

net.milosvasic.fundamental.kotlin

Finally, create your first Kotlin source code file by right clicking on a package you just created and choosing: New → Kotlin File / Class. Give some name to a file, like for example: _First_ , in our case. New created file will appear in your package.

Great! We have now an empty Kotlin file. Lets add some code:

fun main(args: Array<String>) {

println("My first Kotlin application.")

}

This is very simple code that starts console Kotlin application and prints a line of text. As in Java, here we have function called _main_ as entry point of our application. This function does not belong to any class. We will later talk about defining functions, passing arguments and other related stuff.

To run it right click on _.kt_ file and choose _Run._ You will notice console output when build process is done and application is executed.

## Basic Syntax

Before we continue please download code examples for this book:

<http://static.fundamental-kotlin.com/code/Fundamental-Kotlin.zip>

Now, let's see how some basic syntax looks in Kotlin. Open _First.kt_ file.

### Packages

Packages represent basic level of organization of our code. Every _.kt_ file must belong to some package. We should define our package in the top of our _.kt_ file:

package net.milosvasic.fundamental.kotlin

It is not required to match directories and packages. Source files can be placed arbitrarily in the file system!

### Defining functions

Let's see some functions through examples – file _Second.kt_ from code examples.

This function receives two numbers ( _Integers_ ) as a parameters and returns sum:

fun sum(x: Int, y: Int): Int {

return x + y

}

We can simplify it a bit. Lets see new version of that function:

fun sumSimplified(x: Int, y: Int) = x + y

Here we introduced a function with an expression body and inferred return type.

Let's see one function that does not return any value. In Java that was _Void_ return type. In Kotlin, instead of _void_ we have _Unit_.

fun noReturnValue(x: Int, y: Int): Unit {

println("Sum is ${x + y}")

}

Since our function does not return anything, we can leave out _Unit_ return type:

fun noReturnValue2(x: Int, y: Int) {

println("Sum is ${x + y}")

}

### Local variables

As any other programming language Kotlin can define variables. Let's see some examples ( _Variables.kt_ ) from our code examples.

Assigned once, read only variables:

// We provide type and the value:

val x: Int = 1

// Int type is inferred

val y = 1

// Type is required when no initializer is provided:

val z: Int

If we want our variables to be mutable, do this:

var _m: Int = 0_

// Later in your app: m = m + 1 and so on... value will be changed with the new value.

### Comments

Kotlin is working with comments same way as Java (see _Comments.kt_ ):

// Single line comment

/* Multi-line

* comment */

Kotlin has one additional benefit about comments. Unlike Java, Kotlin supports nested multi-line (block) comments!

### String templates

Let's go back to a file _Second.kt_ and the function called _noReturnValue_. Take a look at the following:

_println(_ "Sum is ${x + y}" _)_

You will notice that we used _${ ... }_ string template expression. We reduced code boilerplate we would have in Java. We avoided String concatenation with _+_ operator.

### Conditional expressions

Now let's write one conditional expression ( _ConditionalExpression.kt_ ):

fun conditionalExpressionExample(x: Int, y: Int): Int {

if(x == y){

return 1

} else {

return 0

}

}

And then, present it as expression:

fun conditionalExpressionExample2(x: Int, y: Int) = if (x == y) 1 else 0

### Null

In Kotlin we must tell explicitly that null value is possible ( _NullExample.kt_ ):

/**

* Returns incremented value if passed parameter is positive number

* otherwise returns null.

*/

_fun getMeSomeValueIncremented(x: Int):_ Int? _{_

if (x > 0) return x + 1

return null

}

Magical part is in Int? where we defined our function to return value as Int but it may be _null_ also.

### Type checks and automatic casts

Comparing to Java, Kotlin has ' _is_ ' operator, equivalent to _'instanceof'_. If we are checking a variable that is immutable, there is no need to do the casting.

We have example of instance check in _IsInstance.kt_ :

fun powIfDouble(x: Any): Double {

if (x is Double) {

return Math.pow(x, 2.0);

}

return 0.0;

}

### For loop

Now we will show some examples of using _for_ loop. Code is pretty much self-explanatory.

_ForLoop.kt_ :

fun forLoopExample(numbers: List<Int>) {

for (x in numbers) println("Number $x")

}

And in case we need the current position in loop:

fun forLoopExampleWithIndex(numbers: List<Int>) {

for (x in numbers.indices) println("Number ${numbers[x]}")

}

### While loop

Let's rewrite previous example using _while_ loop:

fun whileLoopExample(numbers: List<Int>) {

var x = 0

while (x < numbers.size) {

println("Number ${numbers[x++]}")

}

}

### When expression

We used to use _switch_ in Java as one of most common logic statements. Kotlin brings us _when_ as more powerful example! Let's take a look of _when_ expression in _WhenExample.kt_ :

fun whenExample(x: Any) {

when (x) {

25.5 -> println(":)")

is Int -> println("Number is $x")

is String -> println(x)

is Boolean -> if (x) println("It's true.")

else -> println("Unknown")

}

}

Just think about endless possibilities _when_ offers to us!

### Ranges

In Kotlin it's easy to define a range, see _Ranges.kt_ :

// Iterating through the range

fun ranges1(x: Int) {

_for (_ x in 0..100 _) println("Number $x")_

}

// Is x in range?

fun ranges2(x: Int) {

_if (_ x !in 0..100 _) println("No x in range")_

}

### Collections

Let's take a look at following example and see what we can do with collections ( _Collections.kt_ ):

fun collectionsExample(words: List<String>) {

// Check if there is some exact word, if yes return

_if_ ("Something to match" in words _) return_

// If no continue with method execution ...

// Let's iterate:

for (x in words) {

println(x)

}

}

fun collectionsExample2(numbers: List<Double>): List<Double> {

// Let's apply some lambdas:

return numbers

__.filter _{_

it > 100

}

__.sortedBy _{ it }_

}

## Idioms

### Data classes

Kotlin has a rich set of idioms to offer to developers. We will take a look at some of them.

If you need to create some _DTO_ _objects_ , then _data class_ is ideal for you ( _MyDataClass.kt_ ):

data class MyDataClass(val name: String, val age: Int) {}

As you can see we put fields in _class_ definition. With this _data class_ we got the following as additional functionalities:

\- Automatic getters and setters

\- equals()

\- hashCode()

\- toString() in human readable form

\- copy()

\- component1(), component2() ... for all fields.

### Default values for function parameters

In Kotlin we may set default values to be used by functions see _DefaultFunctionValue.kt_ :

_fun defaultValueExample(_ x: Int = 0, y: Int = 2 _){_

// Further implementation ...

}

### Traversing a map

Traversing a map in Kotlin is easy. Take a look at _TraverseMap.kt_ :

fun traverseMapExample(map: Map<String, Int>) {

for ((key, value) in map) println("$key : $value")

}

### Read-only collections

Unlike many languages, Kotlin distinguishes between mutable and immutable collections, look at _ReadOnlyCollections.kt_ :

// Gives us read only list

fun getList(): List<Int> {

return listOf(1, 3, 5, 7)

}

// Gives us read only map

fun getMap(): Map<String, Double> {

return mapOf("EUR" to 123.20, "USD" to 110.34, "CHF" to 111.4)

}

And then, we access to members:

fun printMap(key: String) {

val map = getMap()

if (key in map) println(map[key]) else println("There is no such key $key")

}

### Lazy initialization

Kotlin supports lazy initialization. Take a look at the following example _MyLazy.kt_ :

class MyLazy {

_val lazyVar: String_ by lazy() _{_

println("We called lazy initialization.")

"Lazy value"

}

}

We created one simple class with one field which will not be initialized untill it is used. Notice we put _println("We called lazy initialization.") in lazy initialization routine_ , and then call it from our main function:

val lazy = MyLazy()

println(lazy.lazyVar)

println(lazy.lazyVar)

println(lazy.lazyVar)

println(lazy.lazyVar)

println(lazy.lazyVar)

We will have the following console output:

We called lazy initialization.

Lazy value

Lazy value

Lazy value

Lazy value

Lazy value

Print line with message " _We called lazy initialization_ " is executed at the moment we initialized our field - only once. Every other time we have value associated to field so no message is printed again.

### Extending functionalities

Kotlin gives us ability to extend functionality of any class! Let's extend some class ( _ExtendedFunctionalityExample.kt_ ):

class Employee {

fun name(): String {

return "Employee name"

}

}

class ExtendedFunctionalityExample(val e: Employee) {

// We extended Employee class with function that does not exist in original class!

__ fun Employee.age(): Int _{_

return 25

}

fun tryExtendedEmployeeExample() {

println("Name: ${e.name()}, Age: ${e.age()}")

}

}

Let's try it:

val e = Employee()

val ee = ExtendedFunctionalityExample(e)

ee.tryExtendedEmployeeExample()

Console output:

Name: Employee name, Age: 25

### If not null shorthands

To reduce unnecessary code boilerplate Kotlin comes up with more great features such as null shorthands. Let's take a look at the following example:

val files = File("./SomeFile").listFiles()

_println(files_?. _size_?: _"empty")_

Then, in the next example, we will execute statement if null:

_val subscribers = data["subscribers"]_?: _throw IllegalStateException("There is no any subscribers")_

If not null example:

val player = getPlayer()

_player_?. _play("Uriah Heep - Easy Livin.mp3")_

You can check full example in _NullShorthands.kt_ code examples file.

### Return on when statement

Let's see how it looks when we need a returned value based on _when_ expression:

( _ReturnOnWhenExample.kt_ )

fun getCarPrice(model: String): Int {

return when (model) {

"Mercedes" -> 100000

"BMW" -> 95000

"Opel" -> 82000

else -> throw IllegalArgumentException("We do not recognize this model.")

}

}

### Try / Catch

So, we'll continue with previous example and handle case when passed invalid car model ( _TryCatch.kt_ ):

fun tryCatchExample() {

val carModels = listOf("BMW", "Fiat", "Mercedes", "Opel", "Renault")

for (carModel in carModels) {

try {

println("$carModel has a price of ${getCarPrice(carModel)}")

} catch(e: Exception) {

println("Unknown preice for $carModel")

}

}

}

Console output looks like this:

BMW has a price of 95000

We do not recognize this model.

Mercedes has a price of 100000

Opel has a price of 82000

We do not recognize this model.

### If expression

In Kotlin _if_ can return a value! Let's look at _IfExpression.kt_ :

fun getMemberTypeById(id: Int): String {

return if (id == 0) {

"Unregistered"

} else if (id == 1) {

"Registered"

} else if (id == 2) {

"Admin"

} else {

"Unknown"

}

}

### Single-expression functions

In Kotlin we can define function as a single expression:

fun getValue() = 100

Codebase can be significantly reduced.

Let's take a look at more complex exmaple ( _SingleExpressionFunctionExample.kt_ ):

fun obtainCarPrice(carModel: String): Int = when (carModel) {

"Mercedes" -> 100000

"Opel" -> 82000

"Renault" -> 75000

else -> throw IllegalArgumentException("Unknown car model")

}

### Calling methods on an object instance using 'with'

Let's see how we can use _'with'_ to access methods of some instance ( _HandlingInstanceUsingWith.kt_ ):

class Human {

fun walk() {

println("Walking");

}

fun talk() {

println("Talking");

}

fun jump() {

println("Jumping");

}

fun swim() {

println("Swimming");

}

}

fun useHuman(human: Human) {

__ with(human) _{_

walk()

walk()

walk()

jump()

swim()

jump()

walk()

walk()

}

}

Console output:

Walking

Walking

Walking

Jumping

Swimming

Jumping

Walking

Walking

## Basic types

In Kotlin, unlike in Java, everything is an object. In Java, we have primitive types such as: _int, char, byte, float_ and so on. In Kotlin each of this primitives is represented by (and only) by class. Kotlin does not have primitive types!

### Numbers in Kotlin

Here is the list of number classes:

_Double_ – 64 bits

_Float_ – 32 bits

_Long_ – 64 bits

_Int_ – 32 bits

_Short_ – 16 bits

_Byte_ – 8 bits

To represent numbers we can use the following literals:

\- Decimal numbers: _100, 200, 123_...

\- Long decimal numbers: _400L, 10L, 200L_...

\- Hexadecimal numbers: _0x0F..._

\- Floating point numbers: _1.23, 2.16_... Default type used is _Double_ , to use _Float_ define it like 1.23f, 2.16f ...

Kotlin does no support octal literals!

All numbers are stored in _JVM_. Bigger numbers are not the classes that are extending smaller ones or vice versa!

( _Numbers.kt_ )

fun playWithNumbers() {

val a: Int = 1 // a is boxed Int (java.lang.Integer)

var b: Long? = null // We can't pass b directly to a!

b = a.toLong() // We must convert it!

println("a: $a") // prints 1

println("b: $b") // prints 1

print(a.equals(b)) // We compare them

}

So, the conversation between numbers is done by one of methods (each number class has them):

\- _toByte()_ : _Byte_

\- _toShort()_ : _Short_

\- _toInt()_ : _Int_

\- _toLong()_ : _Long_

\- _toFloat()_ : _Float_

\- _toDouble()_ : _Double_

\- _toChar()_ : _Char_

The type is inferred from the context, and arithmetical operations are overloaded for appropriate conversions, for example:

val x = 1L + 1 // Long + Int = Long

All arithmetical operations are defined as operators defined in number classes. Standard set of arithmetical operations is supported, such as: _+, -, /, *_ etc.

Here is the list of bitwise operations available for _Int_ and _Long_ classes:

\- _shl(bits)_ \- signed shift left (in Java: _< <_)

\- _shr(bits)_ \- signed shift right (in Java _> >_)

\- _ushr(bits)_ \- unsigned shift right (in Java _> >>_)

\- _and(bits)_ \- bitwise and

\- _or(bits)_ \- bitwise or

\- _xor(bits)_ – bitwise xor

\- _inv()_ \- bitwise inversion

### Characters in Kotlin

Characters cannot be treated directly as numbers! To convert them use _toInt()_ class method. Each literal character goes in single quotes, for example: ' _1_ ', ' _m_ ', ' _p_ ' and so on. Also, there are some important escape sequences that we will need for sure: _\t_ , _\b_ , _\n_ , _\r_ , _\'_ , _\"_ , _\\\_ and _\$_.

### Booleans in Kotlin

Class _Boolean_ represents _boolean_ type in Kotlin. It has two possible values: _true_ or _false_.

There are 3 major operations we can perform on booleans in Kotlin:

\- _||_ \- lazy disjunction, example: _a || b_

\- _& &_ \- lazy conjunction, example: _a && b_

\- _!_ \- negation, example: _!a || !b_

### Arrays in Kotlin

Let's take a look at the following example: _Arrays.kt_ , it demonstrates Kotlin arrays with self-explanatory code:

fun arraysExample(){

// Array of 10 items which values are genereted by: index + 100

val a = Array(5, { i -> i + 100 })

for(x in a) println("A member: $x")

println("- - - - - - - - - - - - - set 1000 to element at 2")

a[2] = 1000 // or: a.set(2, 1000)

for(x in a) println("A member: $x")

println("- - - - - - - - - - - - - ")

val y = a.get(0)

println("Member at 0 position: $y")

println("- - - - - - - - - - - - - ")

val b = arrayOf(2, 4, 6, "Some string", "One more string", 8, 10)

b[1] = 10 // Replace 4 with 10!

for(x in b) println("B member : $x")

println("- - - - - - - - - - - - - ")

val c = arrayOfNulls<Int>(5)

for(x in c) println("C member: $x")

println("- - - - - - - - - - - - - set values to members")

for (x in c.indices) c[x] = x + 1000 // or: c.set(x, x + 1000)

for(x in c) println("C member: $x")

println("- - - - - - - - - - - - - ")

val d = intArrayOf(10, 100, 1000, 10000)

for(x in d) println("D member: $x")

println("- - - - - - - - - - - - - set values to members")

for (x in d.indices) d[x] = d[x] + 5000 // or: d.set(x, d.get(x) + 5000)

for(x in d) println("D member: $x")

println("- - - - - - - - - - - - - ")

println("A size ${a.size}")

println("B size ${b.size}")

println("C size ${c.size}")

println("D size ${d.size}")

println("- - - - - - - - - - - - - ")

}

Console output:

A member: 100

A member: 101

A member: 102

A member: 103

A member: 104

\- - - - - - - - - - - - - set 1000 to element at 2

A member: 100

A member: 101

A member: 1000

A member: 103

A member: 104

\- - - - - - - - - - - - -

Member at 0 position: 100

\- - - - - - - - - - - - -

B member : 2

B member : 10

B member : 6

B member : Some string

B member : One more string

B member : 8

B member : 10

\- - - - - - - - - - - - -

C member: null

C member: null

C member: null

C member: null

C member: null

\- - - - - - - - - - - - - set values to members

C member: 1000

C member: 1001

C member: 1002

C member: 1003

C member: 1004

\- - - - - - - - - - - - -

D member: 10

D member: 100

D member: 1000

D member: 10000

\- - - - - - - - - - - - - set values to members

D member: 5010

D member: 5100

D member: 6000

D member: 15000

\- - - - - - - - - - - - -

A size 5

B size 7

C size 5

D size 4

\- - - - - - - - - - - - -

### Strings in Kotlin

Strings in Kotlin are immutable. Elements in one _String_ are characters that can be accessed like any other array. To each element we can access using _Iterrator_ , or using _for_ loop.

Let's look at _Strings.kt_ :

val s = "Some string"

// Iterate:

val iterator = s.iterator()

while(iterator.hasNext()) println("Character: ${iterator.next()}")

println("- - - - - - - - - - - - - ")

// For loop:

for(c in s) println("Character: $c")

println("- - - - - - - - - - - - - ")

Console output:

Character: S

Character: o

Character: m

Character: e

Character:

Character: s

Character: t

Character: r

Character: i

Character: n

Character: g

\- - - - - - - - - - - - -

Character: S

Character: o

Character: m

Character: e

Character:

Character: s

Character: t

Character: r

Character: i

Character: n

Character: g

\- - - - - - - - - - - - -

Strings can be defined in several ways:

val s1 = "Some string"

val s2 = "Some\tstring\n"

val s3 = """

Raw string example...

We have multiline here!

"""

## Control flow

It is time to learn about Kotlin's features which we will use to create logic for our software.

### If expression

As we have already mentioned, in Kotlin _If_ is expression. In Kotlin _If_ returns value! Because of that, ternary operator " _condition ? then : else"_ is removed! It does not exist.

The following examples demonstrates it ( _If.kt_ ):

val result = if (x == y) "It is equal." else "It is not equal."

fun ifExample(x: Int, y: Int) {

val result = if (x >= y) {

println("Condition ok.")

true

} else {

println("Condition else.")

false

}

println("Result $result")

}

Execute method:

ifExample(2, 5)

ifExample(2, 2)

ifExample(5, 2)

console output:

Condition else.

Result false

Condition ok.

Result true

Condition ok.

Result true

If you choose to use _If_ as expression rather than statement, your _If_ must use _Else_ part!

### When

_When_ represents replacement for Java's _switch / case_. _When_ can be used either as an expression or as a statement.

_When_ matches its argument against all branches sequentially until some branch condition is satisfied. If it is used as an expression, the value of the satisfied branch becomes the value of the overall expression. If it is used as a statement, the values of individual branches are ignored.

The _else_ branch is evaluated if none of the other branch conditions are satisfied. If _When_ is used as an expression, the _else_ branch is mandatory, unless the compiler can prove that all possible cases are covered with branch conditions. If many cases should be handled in the same way, the branch conditions can be combined with a comma.

Let's check out the following examples ( _When.kt_ ) and see what we can do with _When_ :

// ----- example 1:

fun whenExample(userType: Int) {

when (userType) {

0 -> println("Registered user")

1 -> print("Administrator")

else -> {

println("Unknown")

}

}

}

// ----- example 2:

fun whenExample2(userType: Int) {

when (userType) {

0, 1 -> println("Welcome user.")

else -> println("Permission denied.")

}

}

// ----- example 3:

fun whenExample3(userType: Int){

when (userType) {

filterUserType(userType) -> {

println("Subtype ok")

whenExample2(userType)

}

else -> print("Subtype not ok")

}

}

fun filterUserType(userType: Int): Int {

if(userType >= 0 && userType < 2){

return userType;

}

return -1

}

// ----- example 4:

// Checking ranges:

fun whenExample4(x: Int) {

val from = 0

val to = 100

when (x) {

in from..to -> println("PRECISE")

in (from / 2)..(to / 2) -> print("VERY PRECISE")

50 -> print("STRAIGHT IN TARGET")

else -> print("MISSED")

}

}

// ----- example 5:

fun whenExample5(fullName: String) {

val isJohn = when (fullName) {

is String -> fullName.startsWith("John ")

else -> false

}

}

// ----- example 6:

fun whenExample6(fullName: String) {

when {

fullName.length == 0 -> println("Please enter your name.")

fullName.substring(0, 2).equals("X ") -> println("Hello Mr. X")

fullName.startsWith("John ") && !fullName.endsWith(" Smith") -> println("Hello John!")

fullName.endsWith(" Smith") -> println("Hello agent Smith.")

else -> println("Only secret agents allowed!")

}

}

### For

_For_ loop iterates through everything that provides an iterator and has a member, or extension-function _iterator()_. It must be _Iterator_ whose return type has a member, or extension-function _next()_ , _hasNext()_ that returns _Boolean_.

**All of these three functions need to be marked as** operator **.** A _For_ loop over an array is compiled to an index-based loop that does not create an iterator object.

Let's take a look at example _For.kt_ :

fun forExample(array: Array<String>) {

for ((index, value) in array.withIndex()) {

println("[ $index ][ $value ]")

}

}

### While and Do..While

We will demonstrate both in code example _While.kt_ :

fun whileExample() {

var x = 0

while (x < 100) {

println("X: $x")

x++

}

}

fun doWhileExample() {

var x = 0

do {

println("X: $x")

x++

} while (x < 100)

}

### Jump operators

In Kotlin we have the following jump operators:

\- _return_ , by default it returns value from nearest function or anonymous function

\- _break_ , terminates nearest enclosing loop

\- _continue_ , goes to next step of nearest enclosing loop.

### Jump operator labels

In Kotlin, any expression can be marked with label which has the following form: _@label expression_.

Let's try out labels with break ( _JumpOperatorLabels.kt_ ):

myLoop@ _for (a in 0..x) {_

for (b in 0..y) {

println("[ $a ][ $b ]")

if (b == 10) {

__ break@myLoop _// Does not break current loop, but the one above it!_

}

}

}

then we'll call the method:

labelsExample(20, 20)

console output looks like this:

[ 0 ][ 0 ]

[ 0 ][ 1 ]

[ 0 ][ 2 ]

[ 0 ][ 3 ]

[ 0 ][ 4 ]

[ 0 ][ 5 ]

[ 0 ][ 6 ]

[ 0 ][ 7 ]

[ 0 ][ 8 ]

[ 0 ][ 9 ]

[ 0 ][ 10 ]

### Return with labels

With function literals, local functions and object expression, functions can be nested in Kotlin. Qualified returns allow us to return from an outer function. **The most important use case is returning from a lambda expression!**

Let's take a look at example _ReturnAtLabels.kt_ :

fun returnAtLabelsExample(ints: List<Int>) {

ints.forEach {

if (it == 0) return

println("Item: $it")

}

}

returnAtLabelsExample(arrayListOf(1, 2, 3, 4, 5, 0, 10, 11, 12, 13))

Console output:

Item: 1

Item: 2

Item: 3

Item: 4

Item: 5

fun returnAtLabelsExample2(ints: List<Int>) {

_ints.forEach_ myLabel@ _{_

_if (it == 0)_ return@myLabel

println("Item: $it")

}

}

returnAtLabelsExample2(arrayListOf(1, 2, 3, 4, 5, 0, 10, 11, 12, 13))

Console output:

Item: 1

Item: 2

Item: 3

Item: 4

Item: 5

Item: 10

Item: 11

Item: 12

Item: 13

_Return_ returns from the nearest enclosing function. **Such non-local returns are supported only for lambda expressions passed to inline functions.** If we need to return from a lambda expression, we have to label it and qualify the R _eturn_!

We can achieve the same with the following example:

fun returnAtLabelsExample3(ints: List<Int>) {

_ints._ forEach _{_

_if (it == 0)_ return@forEach

println("Item: $it")

}

}

returnAtLabelsExample3(arrayListOf(1, 2, 3, 4, 5, 0, 10, 11, 12, 13))

Console output:

Item: 1

Item: 2

Item: 3

Item: 4

Item: 5

Item: 10

Item: 11

Item: 12

Item: 13

We can replace lambda expression with anonymous function:

ints.forEach(

fun(value: Int) {

if (value == 0) return

println("Item: $value")

}

)

returnAtLabelsExample4(arrayListOf(1, 2, 3, 4, 5, 0, 10, 11, 12, 13))

Console output:

Item: 1

Item: 2

Item: 3

Item: 4

Item: 5

Item: 10

Item: 11

Item: 12

Item: 13

# Working with objects

It's time to investigate object-oriented side of Kotlin. We will define classes, extend them and do other operations we usually do when dealing with classes. We will see how Kotlin is similar or how it is different to Java.

## Classes

In Kotlin class is defined using the same word we use in Java: _class_.

Let's go through _ClassExamples.kt_ :

// Simple class definition

class Dummy {}

// If there is no body like in previous example

class NoBody

### Constructors

In Kotlin, class can have a primary constructor and one or more secondary constructors. The primary constructor is a part of class header. **If the primary constructor does not have any annotations or visibility modifiers, the constructor keyword can be omitted.**

class Car constructor(val brand: String)

class Plane(val brand: String)

val car = Car("BMW")

val plane = Plane("Boeing")

println(car.brand)

println(plane.brand)

Console output:

BMW

Boeing

The primary constructor can't contain any code. Initialization code can be placed in initializer blocks, which are prefixed with the init keyword. Take a look at example:

class Calculator(val parameter: Int){

_val_ calcualtedValue _: Int_

__ init _{_

__ calcualtedValue = _parameter * 2_

}

}

val calculator = Calculator(2)

println("Calculated value: ${calculator.calcualtedValue}")

Console output:

Calculated value: 4

Let's say that we don't want class to be constructed publicly, we can do it the following way:

_class NotPublicConstructed_ private _constructor(val name: String){_

// ...

}

### Secondary constructors

Let's take a look at the following example:

class Person(val name: String) {

constructor(name: String, year: Int) : this(name) {}

constructor(name: String, year: Int, height: Int) : this(name) {}

}

val person1 = Person("John Smith")

val person2 = Person("John Doe", 1985)

val person3 = Person("John SomeOther", 1987, 190)

The code demonstrates usage of secondary constructor in Kotlin. If we didn't define primary constructor, class will have default – empty constructor, with no arguments.

We instantiated three instances of _Person class_. Each with different constructor. You can also notice that Kotlin does not have word _new_ for instantiation.

### Members

In Kotlin classes can have the following members:

\- Constructors

\- Initialization blocks

\- Functions

\- Properties

\- Nested classes

\- Inner classes

\- Misc object declarations – for example: _companion object_.

### Inheritance

In Java, all classes (who do not extend some other class) are extending _Object_ super class. Kotlin has its super class called Any. From _Any_ class we inherit the following methods:

\- _equals()_

\- _hashCode()_

\- _toString()_

Let's take a look at inheritance example ( _Inheritance.kt_ ):

// Inherits Any

open _class Human_

// Indian extends Human

class Indian : Human()

// Class with non-empty constructor

open class Vehicle(type: String)

// Truck extends Vehicle and it's constructor

class Truck(type: String) : Vehicle(type)

// Train extends Vehicle but has empty constructor.

// Value is passed to parent constructor.

class Train : Vehicle("Civil")

// Another way to extend class

class Bus : Vehicle {

constructor(type: String) : super(type)

}

It is important to note that _class_ can't be extended until it is defined as _Open_! _Open_ is opposite to Java's _final_.

### Overriding

To override method in class we must define it as _open_ in our _super_ class ( _Overriding.tk_ ):

open class Engine {

__ open _fun turnOn() {_

println("Turn on")

}

}

class SuperEngine : Engine() {

__ override _fun turnOn() {_

super.turnOn()

println("Do a special thing!")

}

}

val engine = SuperEngine()

engine.turnOn()

Console output:

Turn on

Do a special thing!

A member marked override is itself open! It may be overridden in subclasses. If you want to prohibit re-overriding, use _final_ : _final override fun_...

### Abstraction

In Kotlin, as in Java, class and some of its members can be declared abstract. An abstract member doesn't have an implementation in its class. Note that we do not need to annotate an abstract class or function with open – it goes without saying! The same applies for interfaces. Also, we can override a non-abstract open member with an abstract one.

Let's take a look at example _Abstraction.kt_ :

abstract class Animal {

__ abstract fun _walk()_

fun run(){

println("run")

}

}

open class Cat : Animal() {

__ override fun _walk() {_

println("walk")

}

}

abstract class BigCat : Cat() {

__ override abstract fun _walk()_

}

### Class companion object

In Kotlin there are no _static_ methods! It is recommended to use _package_ level functions instead.

If you need to write a function that can be called without having a _class_ instance but needs access to the internals of a _class_ , you can write it as a member of an object declaration inside that _class_. If you declare a _companion object_ inside your _class_ , you'll be able to call its members with the same syntax as calling _static_ methods in Java, using only the _class_ name as a qualifier.

Let's take a look at _CompanionObjectExample.kt_ :

class CompanionObjectExample {

__ companion object _StaticObject {_

fun iAmStatic(){

println("I am static!")

}

}

}

Call the static method:

CompanionObjectExample.iAmStatic()

Console output:

I am static!

### Sealed classes

Sealed classes are used for representing restricted class hierarchies. Sealed class value can have one of the types from limited set. Sealed classes are, in a sense, an extension of enum classes. Set of values for an enum type is also restricted, but each enum constant exists only as a single instance, whereas a subclass of a sealed class can have multiple instances which can contain state.

A sealed class can have subclasses, but all of them must be nested inside the declaration of the sealed class itself.

Note that classes which extend subclasses of a sealed class (indirect inheritors) can be placed anywhere, not necessarily inside the declaration of the sealed class.

The key benefit of using sealed classes comes into play when you use them in a _when_ expression. If it's possible to verify that the statement covers all cases, you don't need to add an else clause to the statement.

Lets take a look at example _Sealed.kt_ :

sealed class SuperEnum {

class Human(val race: String) : SuperEnum()

class Animal(val specie: String, val legsCount: Int) : SuperEnum()

object Bacteria : SuperEnum()

}

fun trySuperEnum(superEnum: SuperEnum): String = when (superEnum) {

is SuperEnum.Human -> "Human ${superEnum.race}"

is SuperEnum.Animal -> "${superEnum.specie} with ${superEnum.legsCount} legs."

is SuperEnum.Bacteria -> "Some micro organism ..."

}

Then we call:

println(trySuperEnum(SuperEnum.Human("Indian")))

println(trySuperEnum(SuperEnum.Human("Asian")))

println(trySuperEnum(SuperEnum.Animal("Monkey", 2)))

println(trySuperEnum(SuperEnum.Animal("Horse", 4)))

println(trySuperEnum(SuperEnum.Bacteria))

Console output:

Human Indian

Human Asian

Monkey with 2 legs.

Horse with 4 legs.

Some micro organism...

## Class properties

Let's take a look at example _Properties.kt_ :

class WorkWithProperties {

var x: Int = 0;

var y: Int? = null

val z: Int = 1

}

fun accessProperties(){

val w = WorkWithProperties()

w.y = 10

val x = w.x

val y = w.y

val z = w.z

}

Properties defined as _var_ are mutable. Read-only properties are defined as _val_.

To define getters and setters for a _class_ fields we should do the following ( _GetterSetter.kt_ ):

class GetterSetter {

var x: Int

get() = x

set(value) {

x = value

}

var y: String

get() = y

set(value) {

y = value

}

var z: Boolean = true

_private set_ // Setter can't be accessed publicly anymore!

get() = z

}

### Properties with late initialization

Let's take a look at example and see how properties can be late-initialized ( _LateInit_.kt):

class SomeExampleClass {

fun printMe() {

println("I am late initialized!")

}

}

class TryLateInit {

lateinit var x: SomeExampleClass

fun printMe() {

x = SomeExampleClass()

x.printMe()

}

}

Since it is expected that properties are initialized in constructor, sometimes that is not what we want. For that particular situation we mark our property with _lateinit_. _Lateinit_ may be only used with _var_ properties who are defined in _class_ body with no custom getter and setter! The type of property must not be non-null or primitive.

## Interfaces

In Kotlin, the way we work with _interfaces_ is the same as in Java. Let's take a look at example _Interfaces.kt_ :

interface Audio {

fun volumeUp();

fun volumeDown();

fun setVolume(volume: Int)

}

class Tv : Audio {

override fun volumeUp() {

println("Volume up")

}

override fun volumeDown() {

println("Volume down")

}

override fun setVolume(volume: Int) {

println("Set volume to $volume")

}

}

_Interfaces_ can have _properties_. _Property_ can be abstract or with value assigned.

interface Video {

val brightness: Int

val contrast: Int

get() = 100

fun play() {

println("Play")

}

fun pause()

}

open class MultimediaDevice : Audio {

override fun volumeUp() {

println("Volume up")

}

override fun volumeDown() {

println("Volume down")

}

override fun setVolume(volume: Int) {

println("Set volume to $volume")

}

}

class DvdPlayer : Tv(), Video {

__ override val brightness: Int = 100

override fun pause() {

println("Pause")

}

}

Pay attention that _interfaces_ in Kotlin can have methods with implementation.

## Visibility modifiers

In Kotlin _classes, objects, interfaces, constructors, functions, properties_ and their _setters_ can have _visibility modifiers_. Getters always have the same visibility as the property.

There are:

private _\- visible only inside the current scope_

protected _– visible for the current scope and all that extend it_

public \- visible everywhere

internal _– visible everywhere inside the current module_

The default visibility is _public_.

## Extensions

Kotlin provides ability to extend class with new functionality without having to inherit from class or use any type of design pattern such as Decorator.

Extensions do not modify parent classes! They are just extending it. Extensions do not insert a new function to a class but create a _callable_ inside a class where we are extending. Let's look at the example ( _Extensions.kt_ ):

class Parent {

fun doSomething() {

println("Do something...")

}

}

class MyClass {

fun Parent.doSomething() {

this.doSomething()

println("And the extended part.")

}

fun Parent.doSomething(x: Int) {

println("Extended with parameter passed")

}

fun Parent.newStuff() {

println("Extended with new method")

}

fun tryExtensions(parent: Parent) {

with(parent) {

doSomething()

doSomething(5)

newStuff()

}

}

}

Then call it:

val p = Parent()

p.doSomething()

println("- - - - -")

val m = MyClass()

m.tryExtensions(p)

println("- - - - -")

Console output:

Do something...

\- - - - -

Do something...

Extended with parameter passed

Extended with new method

\- - - - -

### Extending class properties

Kotlin has ability to extend _class_ properties. Let's see the example _ExtendingProperties.kt_ :

class ToBeExtended {

val a = 15

}

class ExtendsProperty {

val ToBeExtended.b: Int

get() = 25

fun tryPropertyExtension(e: ToBeExtended) {

println("A: ${e.a}")

println("A: ${e.b}")

}

}

Try it:

val t = ToBeExtended()

val e = ExtendsProperty()

e.tryPropertyExtension(t)

Console output:

A: 15

A: 25

### Extending companion object

If some _class_ has _companion object_ it is possible to be extended by other class.

Let's take a look at example _ExtendingCompanionObject.kt_ :

class HasCompanion {

companion object {

val a = 10

fun printA() {

println("A: $a")

}

}

}

class ExtendsCompanioObjectClass {

_fun_ HasCompanion.Companion.printB() _{_

println("B: ${ a + 100 }")

}

fun tryExtendingCompanionObject(){

HasCompanion.printA()

HasCompanion.printB()

}

}

We call it:

val e = ExtendsCompanioObjectClass()

e.tryExtendingCompanionObject()

Console output:

A: 10

B: 110

## Data classes

For classes that are used for storing data Kotlin offers feature called _data classes_.

Let's take a look at the following example _DataClassExample.kt_ :

data class Employee(val name: String, val age: Int) {}

The compiler automatically offers the following features for each _data class_ :

\- equals()

\- hashCode()

\- toString() in human readable form

\- componentN() functions corresponding to the properties in their order of declaration

\- copy()

If any of these methods is explicitly defined in our class it will not be generated.

Each _data class_ needs to fulfill some conditions:

\- Primary constructor needs to have at least one parameter

\- All primary constructor properties must define as _val_ or _var_

\- _Data classes_ cannot be: _abstract_ , _inner_ , _sealed_ or _open_

\- _Data classes_ cannot extend other classes, they can implement _interfaces._

Let's take a look at example of data class with default values for the fields:

data class Worker(val name: String = "Unknown", val age: Int = 1970) {}

### Copying data classes

Let's take a look at the example _CopyingDataClasses.kt_ :

fun tryDataClassCopying(){

val p = Person("John Smith", 1985)

val p2 = p.copy()

val p3 = p.copy(age = 1990)

val p4 = p.copy("John Doe")

println(p)

println(p2)

println(p3)

println(p4)

}

Running _tryDataClassCopying()_ console output:

Person(name=John Smith, age=1985)

Person(name=John Smith, age=1985)

Person(name=John Smith, age=1990)

Person(name=John Doe, age=1985)

## Generics

As in Java, Kotlin can define classes with _type_ parameters.

Let's take a look at example that shows us generics in Kotlin ( _Generics.kt_ ):

class Container<T>(val data: T) {

fun printIt(){

println("We have value [ $data ]")

}

}

fun tryGenerics(){

val data1 = Container(1)

val data2 = Container("Some string")

val data3 = Container(true)

data1.printIt()

data2.printIt()

data3.printIt()

}

Console output (running _tryGenerics()_ method):

We have value [ 1 ]

We have value [ Some string ]

We have value [ true ]

Ok, here we demonstrated basic usage of generics. Let's take a look what we can do if we want to be more precise about class types ( _MoreGenerics.kt_ ):

abstract class Car(var model: String) {

abstract var name: String

}

class Bmw(model: String) : Car(model) {

override var name: String = "Bmw"

}

class Mercedes(model: String) : Car(model) {

override var name: String = "Mercedes"

}

// 'in' word means that CarWash instance will be specialized for certain car type

// also that means that type may be consumed, but never produced!

_class CarWash <_in C : Car _> {_

fun washCar(car: C) {

println("Washing ${car.name} ${car.model}")

}

}

// 'out' word means that CarFactory instance will be specialized for certain car type

// also that means that type may be produced, but never consumed!

_abstract class CarFactory <_out C : Car _> {_

abstract fun forgeCar(model: String): C

}

class BmwFactory : CarFactory<Bmw>() {

override fun forgeCar(model: String): Bmw {

return Bmw(model)

}

}

class MercedesFactory : CarFactory<Mercedes>() {

override fun forgeCar(model: String): Mercedes {

return Mercedes(model)

}

}

fun tryMoreGenerics() {

val bmwFactory = BmwFactory()

val mercedesFactory = MercedesFactory()

val bmw = bmwFactory.forgeCar("M4")

val mercedes = mercedesFactory.forgeCar("AMG GT")

val bmwCarWasher: CarWash<Bmw> = CarWash()

val mercedesCarWasher: CarWash<Mercedes> = CarWash()

val generalCarWasher: CarWash<Car> = CarWash()

bmwCarWasher.washCar(bmw)

_// bmwCarWasher.washCar(mercedes)_ // Can't wash it here! :)

mercedesCarWasher.washCar(mercedes)

generalCarWasher.washCar(bmw)

generalCarWasher.washCar(mercedes)

}

In this example we demonstrated practical use of _generics_ in Kotlin. Please pay attention to comments in code and bolded code.

## Generic functions

Let's take a look at the example _GenericFunctions.kt_ and see how Kotlin is dealing with generic functions:

abstract class Engine {

abstract val power: Long

override fun toString(): String{

return "Engine(power=$power)"

}

}

class RocketEngine : Engine() {

override val power: Long

get() = 1000

}

class TruckEngine : Engine() {

override val power: Long

get() = 100

}

class EngineDiagnostics {

_fun_ <T : Engine> _checkEngine(engine: T) {_

println(engine)

}

}

fun tryGenericFunctions(){

val truckEngine = TruckEngine()

val rocketEngine = RocketEngine()

val diagnostics = EngineDiagnostics()

diagnostics.checkEngine(truckEngine)

diagnostics.checkEngine(rocketEngine)

}

Console output:

Engine(power=100)

Engine(power=1000)

## Java's 'EXTENDS'

In Java we have _extends_ keyword which mean that some type we pass must extend some other. In Kotlin we do it like this ( _Extends.kt_ ):

abstract class Airplane {

abstract fun decribeMe();

}

class Boeing : Airplane() {

override fun decribeMe() {

println("Being")

}

}

class Airbus : Airplane() {

override fun decribeMe() {

println("Airbus")

}

}

class AirplaneDescriptor {

_fun_ <T : Airplane> _describe(airplane:_ T _) {_

airplane.decribeMe()

}

}

fun tryExtendsExample(){

val airplane1 = Airbus()

val airplane2 = Boeing()

val descriptor = AirplaneDescriptor()

descriptor.describe(airplane1)

descriptor.describe(airplane2)

}

Running _tryExtendsExample()_ method gives console output:

Airbus

Boeing

## Nested classes

Let's take a look at _Nested.kt_ :

class Nested1 {

val a = 0

class Nested2 {

val a = 1

class Nested3 {

val a = 2

}

}

}

fun tryNested() {

val n1 = Nested1()

val n2 = Nested1.Nested2()

val n3 = Nested1.Nested2.Nested3()

println("Values ${n1.a}, ${n2.a}, ${n3.a}")

}

Executing _tryNested()_ gives us the following console output:

Values 0, 1, 2

## Inner classes

If we need access to members of outer class, we should mark our class as _inner_. Our _inner_ class has a reference to object of an outer class. Let's take a look at the example _Inner.kt_ :

class InnerExample {

val a = 100

__ inner _class Inner {_

val b = a

}

}

fun tryInner() {

val x = InnerExample().Inner()

println("Value of b is: ${x.b}")

}

Console output:

Value of b is: 100

## Enumeration

Let's make some enums in Kotlin ( _Enums.kt_ ):

enum class TIME {

MICROSECOND,

MILLISECOND,

SECOND,

MINUTE,

HOUR,

DAY,

WEEK,

MONTH

}

enum class COUNTRY(val capital: String) {

ITALY("Rome"),

SPAIN("Madrid"),

RUSSIA("Moscow"),

SCOTLAND("Edinburgh")

}

fun trySomeEunums(){

println("Time unit: ${TIME.MILLISECOND}")

println("Time unit: ${TIME.SECOND}")

println("Time unit: ${TIME.MINUTE}")

println("Country vs capital: ${COUNTRY.ITALY} -> ${COUNTRY.ITALY.capital}")

println("Country vs capital: ${COUNTRY.SPAIN} -> ${COUNTRY.SPAIN.capital}")

println("Country vs capital: ${COUNTRY.RUSSIA} -> ${COUNTRY.RUSSIA.capital}")

}

Console output:

Time unit: MILLISECOND

Time unit: SECOND

Time unit: MINUTE

Country vs capital: ITALY -> Rome

Country vs capital: SPAIN -> Madrid

Country vs capital: RUSSIA -> Moscow

Let's take a look at the following example ( _EnumsMore.kt_ ):

enum class DEVICE_CAPABILITIES {

POWER_ON {

override fun execute() {

println("Powering on")

}

},

POWER_OFF {

override fun execute() {

println("Powering off")

}

},

MUTE {

override fun execute() {

println("Muting audio")

}

},

VOLUME_UP {

override fun execute() {

println("Vol +")

}

},

VOLUME_DOWN {

override fun execute() {

println("Vol -")

}

};

abstract fun execute()

}

fun doMoreEnumsStuff() {

val operations = listOf<DEVICE_CAPABILITIES>(

DEVICE_CAPABILITIES.POWER_ON,

DEVICE_CAPABILITIES.VOLUME_UP,

DEVICE_CAPABILITIES.VOLUME_UP,

DEVICE_CAPABILITIES.VOLUME_UP,

DEVICE_CAPABILITIES.POWER_OFF

)

for (operation in operations) {

operation.execute()

}

}

And check the console output when _doMoreEnumsStuff()_ method is executed:

Powering on

Vol +

Vol +

Vol +

Powering off

And the final example, just like in Java we can work with enum constants ( _EnumConstants.kt_ ):

enum class PLANETS {

EARTH,

MARS,

PLUTO

}

fun tryEnumConstantsStuff() {

// Returns PLUTO enum item:

println("Value of: ${PLANETS.valueOf("PLUTO")}")

// Throws exception:

// println("Value of: ${PLANETS.valueOf("VENUS")}")

// Returns array containing all enum items.

println("Values size: ${PLANETS.values().size}")

}

Console output:

Value of: PLUTO

Values size: 3

## Kotlin Object

Let's take a look at example that follows. Here we will create an object of an anonymous class passed to method that expects it ( _AnonymousObject.kt_ ):

abstract class _Command {_

__ abstract fun _execute()_

}

class Executor : Command() {

private val commands = mutableListOf<Command>()

_fun addCommand(_ command: Command _) {_

commands.add(command)

}

override fun execute() {

for (command in commands) {

command.execute()

}

}

}

fun tryAnonymousObjects() {

val executor = Executor()

executor.addCommand(object : Command() {

override fun execute() {

println("Starting session.")

}

})

executor.addCommand(object : Command() {

override fun execute() {

println("Logging in.")

}

})

executor.addCommand(object : Command() {

override fun execute() {

println("Launch app 1")

}

})

executor.addCommand(object : Command() {

override fun execute() {

println("Launch app 2")

}

})

executor.addCommand(object : Command() {

override fun execute() {

println("Logging out")

}

})

executor.addCommand(object : Command() {

override fun execute() {

println("Stopping session")

}

})

executor.execute()

}

Console output:

Starting session.

Logging in.

Launch app 1

Launch app 2

Logging out

Stopping session

Let's take a look at another powerful example using _object_ ( _MoreObject.kt_ ):

// It is crucial to be 'open'!

open class Computer(cpuCores: Int, memoryInGigabytes: Int) {

open val cores: Int = cpuCores

open val memory: Int = memoryInGigabytes

}

interface Gpu {

fun displayImage()

}

interface SoundCard {

fun playSound()

}

fun tryMoreObject() {

_val myComputer =_ object : Computer(8, 64), Gpu, SoundCard _{_

override fun displayImage() {

println("Displaying image.")

}

override fun playSound() {

println("Playing sound")

}

}

println("My computer [ cpu cores: ${myComputer.cores} ][ memory: ${myComputer.memory}GB ]")

myComputer.displayImage()

myComputer.playSound()

}

Console output:

My computer [ cpu cores: 8 ][ memory: 64GB ]

Displaying image.

Playing sound

In the following example, the simplest possible, we'll use an object just as a holder to store some values ( _SimpleObject.kt_ ):

fun simpleObjectExample(){

val obj = object {

var x = 0

var y = 1

}

println("Object [ ${obj.x} ][ ${obj.y} ]")

obj.x = 10

obj.y = 11

println("Object [ ${obj.x} ][ ${obj.y} ]")

}

Console output:

Object [ 0 ][ 1 ]

Object [ 10 ][ 11 ]

Finally let's take a look at last example of using Kotlin _object_ ( _ObjectVariablesAccess.kt_ ):

fun countExecution(){

val executor = Executor()

var leftExecuted = 0

var rightExecuted = 0

val left = object: Command(){

override fun execute() {

println("LEFT")

leftExecuted++

}

}

val right = object: Command(){

override fun execute() {

println("RIGHT")

rightExecuted++

}

}

executor.addCommand(left)

executor.addCommand(left)

executor.addCommand(left)

executor.addCommand(right)

executor.addCommand(right)

executor.addCommand(left)

println("LEFT vs RIGHT, [ ${leftExecuted} ][ ${rightExecuted} ]")

executor.execute()

println("LEFT vs RIGHT, [ ${leftExecuted} ][ ${rightExecuted} ]")

}

Console output:

LEFT vs RIGHT, [ 0 ][ 0 ]

LEFT

LEFT

LEFT

RIGHT

RIGHT

LEFT

LEFT vs RIGHT, [ 4 ][ 2 ]

As you can see we can access to variables of enclosed scope.

## Singleton

In Kotlin, we can use _object_ , _companion object_ to create _singleton_. Let's take a look at _Singleton.kt_ :

_class SingletonExample_ private constructor() {

companion object {

private val instance = SingletonExample()

fun instance(): SingletonExample = instance

}

var x = 0

fun printX() {

println("X: ${x}.")

}

}

fun trySingleton() {

val example1 = SingletonExample.instance()

val example2 = SingletonExample.instance()

val example3 = SingletonExample.instance()

example1.x = 101

println("- - - - - - - -")

example1.printX()

example2.printX()

example3.printX()

example2.x = 202

println("- - - - - - - -")

example1.printX()

example2.printX()

example3.printX()

example3.x = 303

println("- - - - - - - -")

example1.printX()

example2.printX()

example3.printX()

}

Console output:

\- - - - - - - -

X: 101.

X: 101.

X: 101.

\- - - - - - - -

X: 202.

X: 202.

X: 202.

\- - - - - - - -

X: 303.

X: 303.

X: 303.

## Delegating behavior

Let's delegate some behavior. In Kotlin, we delegate behavior using _by_ word. Let's take a look into one very simple and powerful example ( _Delegate.kt_ ):

interface Flying {

fun fly()

}

class Plane : Flying {

override fun fly() {

println("PLANE")

}

}

class Zeppelin : Flying {

override fun fly() {

println("ZEPPELIN")

}

}

class Traveling(fly: Flying) : Flying by fly {

}

fun delegateExample() {

val plane = Plane()

val zeppelin = Zeppelin()

val travelByPlane = Traveling(plane)

val travelByZeppelin = Traveling(zeppelin)

travelByPlane.fly()

travelByZeppelin.fly()

}

Console output:

PLANE

ZEPPELIN

## Delegating properties

In Kotlin we can delegate class properties. There are some cases when we need them, for example when we need _lazy initialization_.

To delegate some properties we will use by word as we did in previous example.

Let's take a look into one simple example of delegated properties ( _DelegateProperties.kt_ ):

class ToBeDelegated() {

_var value: Int_ by Delegator()

}

/*

* ReadWriteProperty:

* Base interface that can be used for implementing property delegates of read-write properties.

*/

class Delegator() : ReadWriteProperty<Any, Int> _{_

var value = 0

__ override fun getValue(thisRef: Any, property: KProperty<*>): Int _{_

println("Value [ GET ][ ${property.name} ]")

return value

}

override fun setValue(thisRef: Any, property: KProperty<*>, value: Int) _{_

println("Value [ SET ][ ${property.name} ][ ${value} ]")

this.value = value

}

}

fun tryPropertiesDelegate() {

val x = ToBeDelegated()

val y = ToBeDelegated()

val z = ToBeDelegated()

x.value = 100

y.value = 200

z.value = 300

println("- - - - - - - - - - - - - - - - - - ")

println("x's val: ${x.value}")

println("y's val: ${y.value}")

println("z's val: ${z.value}")

}

Console output:

Value [ SET ][ value ][ 100 ]

Value [ SET ][ value ][ 200 ]

Value [ SET ][ value ][ 300 ]

\- - - - - - - - - - - - - - - - - -

Value [ GET ][ value ]

x's val: 100

Value [ GET ][ value ]

y's val: 200

Value [ GET ][ value ]

z's val: 300

The syntax is:

val/var <property name>: <Type> by <expression>

The expression after by is the _delegate_ , because _get()_ / _set()_ corresponding to the property will be delegated to its _getValue()_ and _setValue()_ methods.

These are main delegate types:

\- Delegates,

_object Delegates_

Standard property delegates.

\- ObservableProperty,

abstract class ObservableProperty<T> : ReadWriteProperty<Any?, T>

Implements the core logic of a property delegate for a read/write property that calls callback functions when changed.

\- ReadOnlyProperty,

interface ReadOnlyProperty<in R, out T>

Base interface that can be used for implementing property delegates of read-only properties.

\- ReadWriteProperty,

interface ReadWriteProperty<in R, T>

Base interface that can be used for implementing property delegates of read-write properties.

## Property Delegation Requirements

So, for objects delegation we must fulfill the following requirements:

\- For read only property delegate has to provide _getValue_ method that takes parameters: receiver (the same or a supertype of the property owner) and metadata (KProperty<*> or its super type).

\- For mutable property delegate has to provide one more method: _setValue_ that takes parameters: receiver (same as above), metadata (same as above) and new value to be set.

These functions can be provided into two ways:

\- As member functions of delegated class

\- As extension functions.

## Standard Delegates

We will take a look at most common and most useful Kotlin standard delegates.

### Lazy

To do lazy initialization we will use _lazy_ delegate. Let's take a look at example ( _Lazy.kt_ ):

class UsesLazy {

_val myLazyValue: String_ by lazy _{_

println("I am initializing this lazy value!")

"My lazy value!"

}

}

fun useLazy(){

val usesLazy: UsesLazy = UsesLazy()

val a: String = usesLazy.myLazyValue

val b: String = usesLazy.myLazyValue

val c: String = usesLazy.myLazyValue

}

Console output:

I am initializing this lazy value!

By default, the evaluation of lazy properties **is** synchronized! The value is computed only in one thread, and all threads will see the same value.

### Observable

Next delegate we will demonstrate is _observable_. Let's take a look at example ( _Observable.kt_ ):

class ObservableExample {

_var toBeDelegated: String_ by Delegates.observable("Initial value!") _{_

__ property, oldValue, newValue ->

__ println("[ old: $oldValue ][ new: $newValue ]")

}

}

fun observeValueChanges(){

val observe = ObservableExample()

observe.toBeDelegated = "Some new value"

observe.toBeDelegated = "And some more..."

observe.toBeDelegated = "And more... ;)"

}

We will execute method _observeValueChanges()_ to trigger observable delegate and get the following console output:

[ old: Initial value! ][ new: Some new value ]

[ old: Some new value ][ new: And some more... ]

[ old: And some more... ][ new: And more... ;) ]

## Storing Properties in a Map

In Kotlin we might want to store our properties in a map. Let's take a look into example that does that ( _MapProperties.kt_ ):

class Employee(val map: Map<String, Any?>) {

_val firstName: String_ by map

_val lastName: String_ by map

_val yearOfBirth: Int_ by map

}

fun tryMapProperties() {

val e = Employee(

mapOf(

"firstName" to "John",

"lastName" to "Smith",

"yearOfBirth" to 1985

)

)

println("Employee [ ${e.firstName} ${e.lastName} ][ ${e.yearOfBirth} ]")

}

Console output:

Employee [ John Smith ][ 1985 ]

# Functions and Lambdas

It's time to focus on Kotlin functions and lambdas and see how to use them.

## Working with Functions

As we already mentioned many times functions in Kotlin are declared using word _fun_. Functions are called using traditional approach:

val result = execute(25)

### Passing Arguments

We also demonstrated how to pass arguments to these functions. To provide default arguments we should do something like this:

fun calculate(a: Int, b: Int = 10, c: Int = 100){ ... }

### Named Arguments

In Kotlin function parameters can be named. Let's take a look at example _NamedParameters.kt_ :

fun addEmployee(name: String, year: Int, address: String) {

}

// Let's call method:

fun namedParametersExaple() {

addEmployee(

name = "John Smith",

year = 1985,

address = "Avenue 666"

)

}

### Unit is Void

In Java we have functions that do not return any value, returning _void_. Kotlin equivalent for this is _unit_. Functions that are returning _unit_ may be represented like this:

fun doSomething(): Unit {

print("Unit is Void")

}

or

fun doSomething() {

print("Unit is Void")

}

_Unit_ return type declaration is optional!

### Single-Expression functions

In Kotlin functions can be declared as single-expression:

fun getX(): Int = x

or

fun getX() = x

Declaring return type is optional!

### Variable argument functions

In Kotlin, as in Java it is possible to define a function with variable number of arguments ( _Vararg.kt_ ):

_fun sum(_ vararg args: Int _) {_

var sum = 0

for (x in args) {

sum += x

}

println("Sum: $sum")

}

fun trySum(){

_sum(_ 1, 3, 6, 10, 1, 2, 3, 4 _)_

}

Console output:

Sum: 30

### Local functions

Kotlin supports local functions, functions defined inside other functions!

Let's take a look at example _LocalFunctions.kt_ :

fun worker() {

fun doWork(work: String) {

println("Working [ $work ]")

}

doWork("Importing user data")

doWork("Processing user data")

doWork("Exporting user data")

}

Console output:

Working [ Importing user data ]

Working [ Processing user data ]

Working [ Exporting user data ]

## Generic Functions

Once again let's take a look at example of generic functions in Kotlin ( _GenericFunctions.kt_ ):

fun <T> genericFunctionsExample(x: T){

println("Value: $x")

}

fun tryGenericFunctionsExampe(){

genericFunctionsExample(5)

genericFunctionsExample("Some word!")

genericFunctionsExample('c')

genericFunctionsExample(5.55)

}

Console output:

Value: 5

Value: Some word!

Value: c

Value: 5.55

As you can see generic functions in Kotlin are very similar to Java.

## Tail-recursive functions

Kotlin comes with support for _tail-recursion_. _Tail-recursion_ is replacement for loops (comes from functional programming world). Let's take a look at one simple example (TailRecursion.kt):

tailrec _fun tailRecursiveExample(word: String) {_

if (word.length == 1) {

println("--- end")

} else {

println(word)

tailRecursiveExample(word.substring(0..(word.length - 2)))

}

}

fun tryTailRecursiveExample() {

tailRecursiveExample("My word")

}

Console output:

My word

My wor

My wo

My w

My

My

\--- end

When a function is marked with the tailrec the compiler optimizes the recursion. As result we have a fast and efficient loop!

# Higher-Order Functions and Lambdas

It's time to face high-order functions and lambdas in Kotlin, very powerful tool for our everyday development.

## Higher-Order Functions

In Kotlin a _higher-order functions_ are the ones which use other functions as arguments or return it. Let's take a look at example ( _HigherOrder.kt_ ):

fun higherOrderExample(execute: () -> String): String {

return execute.invoke()

}

fun printString(): String {

return "Some string..."

}

fun useHigherOrderExample() {

val string = higherOrderExample(::printString)

println(string)

}

Console output:

Some string...

The same can be achieved **using lambda expressions** :

fun useHigherOrderExampleLambda() {

val string = higherOrderExample { "Yet some other string" }

println(string)

}

Console output:

Yet some other string

## Lambda Expressions and Anonymous Functions

_Lambda expression_ or _anonymous function_ is a function that is not declared but passed as expression.

In previous example we demonstrated usage of _lambda_ function passed as an argument to other function.

One good example of expression can be the following:

fun welcome(e: Employee): String = println("Welcome ${e.name} ${e.lastName}")

## Function Types

So far we passed some functions as arguments to other functions. To pass it we must specify function as a type. Let's take a look at example of passing a function that takes two integer arguments as parameters and returns double:

_fun calculate(operation:_ (Int, Int) -> Double _): Double { ... }_

## Lambda Expression Syntax

We will demonstrate _lambda-expression_ syntax with the following example:

_val x =_ { a: Int, b: Int -> a + b }

println(x.invoke(2, 4))

Console output:

6

Then, the same thing in different way:

_val x:_ (Int, Int) -> Int = { a, b -> a + b }

println(x.invoke(2, 4))

Console output:

6

## Anonymous Functions

An anonymous function is similar to regular functions except that its name is omitted. Its body can be an expression or it can be a block.

Let's take look at examples in _Anonymous.kt_ :

fun example1(){

_val f =_ fun(x: Int, y: Int): Int = x + y

f.invoke(1, 2)

}

fun example2(){

_val f =_ fun(x: Int, y: Int): Int {

return x + y

}

val z = 10 + f.invoke(100, 1000)

}

## Closures

A lambda expression, anonymous function, local function and an object expression can access its closure. The variables declared in the outer scope.

Let's take a look at the following example ( _Closures.kt_ ):

fun tryClosures() {

val values = listOf<Int>(2, 4, 6, 8, 10)

__ var result = 0

values.forEach {

__ result += it

}

println("Result: $result")

}

Console output:

Result: 30

# Inline Functions

Using higher-order functions has certain drawbacks:

\- Each function is an object

\- It captures a closure

\- Memory allocations and virtual calls introduce runtime overhead

Using inline functions can solve this and resolve drawbacks.

Let's take a look at example of inline functions ( _Inline.kt_ ):

inline _fun inlined(function: () - > Unit) {_

function.invoke()

}

fun usedByInlined() {

println("Inlined")

}

fun useInlinedExample() {

inlined ( ::usedByInlined )

}

Console output:

Inlined

Now, let's consider the following situation: we are using inline function, which accepts another function that should not be inlined ( _Noinline.kt_ ):

fun doSomething1() {

println("Do something 1")

}

fun doSomething2() {

println("Do something 2")

}

inline _fun noinlineExample(something1: () - > Unit, _noinline _something2: () - > Unit) {_

something1.invoke()

something2.invoke()

}

fun useNoinlineExample() {

noinlineExample(

::doSomething1,

::doSomething2

)

}

Console output:

Do something 1

Do something 2

As we saw we ignored inlining using _noinline_ word.

The inline modifier affects both the function and the lambda arguments. Everything will be inlined in the call and it will gain us performance!

# Misc

We are approaching the end of this book. We will cover miscellaneous features Kotlin has to offer (and maybe Java doesn't).

## Destructuring

In Kotlin it's possible to _destructure_ class into several variables. For example:

val (brand, model) = car

This can be very convenient if we want to return multiple results from function. Let's say we define a data class holding values representing function result, we may use it like this:

val (a, b, c) = myFunction()

Also, we can use the same approach for loops:

for ((a, b) in collection)

or

_for((key, value) in map)_.

## Ranges

In Kotlin we can define ranges. Let's take a look at the examples:

for (x in 0..10)

for (x in 10 downto 0)

for (x in 0..10 step 2)

for (x in 10 downto 0 step 2)

Ranges implements interface from the library: ClosedRange<T> so desired behavior is achieved.

## Type Checks and Casts

We will demonstrate some type checks:

_if (a_ is _String) // If a is instance of String_

_if (a_!is _String) // If a is not instance of String_

And example for casting:

fun castCheck(a: Any) {

if (a is String) {

println(a) // a is automatically cast to String!

}

}

We don't need to add " _(String) a ..._ " as we would do in Java! This work for both _when-expressions_ and _while-loops_! Smart casts do not work when the compiler can't guarantee that the variable cannot change between the check and the usage.

## This

Let's take a look at example showing usage of Java's _this_ equivalent ( _This.kt_ ):

class ThisExample {

var a: String = "Default a"

fun changeA(a: String){

__ this@ThisExample _.a = a_

}

}

## Equality

Kotlin recognizes two types of equality:

\- Equality by reference

\- Equality by structure

Let's take a look at _Equality.kt_ example:

data class _TestEquality(val a: String, val b: Int) {_

}

fun equalityExample(){

val a = TestEquality("Some string", 2)

val b = TestEquality("Some string", 2)

val c = a

println("a === b: ${ a === b }")

println("a === c: ${ a === c }")

println("a !== b: ${ a !== b }") // Not equal by reference

println("a !== c: ${ a !== c }") // Not equal by reference

println("a == b: ${ a == b }")

println("a == c: ${ a == c }")

}

Console output:

a === b: false

a === c: true

a !== b: true

a !== c: false

a == b: true

a == c: true

If our class is not _data class_ comparing using _==_ (equality by structure) would return us _false_ instead of _true_!

## Operator overloading

Let's take a look at operator overloading example in Kotlin (OperatorOverloading.kt):

class OvrldExmpl(var value: String) {

__ operator fun plus _(toAdd: OvrldExmpl): OvrldExmpl {_

return OvrldExmpl(value + ", " + toAdd.value)

}

}

fun operatorOverloadingExample() {

val a = OvrldExmpl("One")

val b = OvrldExmpl("Two")

val c = OvrldExmpl("Three")

_val d =_ a + b

_val e =_ a + b + c

println("A: ${a.value}")

println("B: ${b.value}")

println("C: ${c.value}")

println("D: ${d.value}")

println("E: ${e.value}")

}

Console output:

A: One

B: Two

C: Three

D: One, Two

E: One, Two, Three

We defined plus operation for our class using modifier _operator_ for the function that has appropriate name.

Here is the list of pairs expression name to operator function name:

+a → a.unaryPlus()

-a → a.unaryMinus()

!a → a.not()

a++ → a.inc()

a-- → a.dec()

a + b → a.plus(b)

a – b → a.minus(b)

a * b → a.times(b)

a / b → a.div(b)

a % b → a.mod(b)

a in b → b.contains(a)

a !in b → !b.contains(a)

a[i] → a.get(i)

a[i, j] → a.get(i, j)

a[i_1,..., i_n] → a.get(i_1,..., i_n)

a[i] = b → a.set(i, b)

a[i, j] = b → a.set(i, j, b)

a[i_1,..., i_n] = b → a.set(a_1,..., a_n, b)

a() → a.invoke()

a(i) → a.invoke(i)

a(i_1,..., a_n) → a.invoke(a_1,..., a_n)

a+=b → a.plusAssign(b)

a-=b → a.minusAssign(b)

a*=b → a.timesAssign(b)

a == b → a?.equals(b) ?: b === null

a !=b → !(a?.equals(b) ?: b ===null)

a>b → a.compareTo(b) > 0

a<b → a.compareTo(b) < 0

a>=b → a.compareTo(b) >= 0

a<=b → a.compareTo(b) <= 0

## Null Safety

In Kotlin working with _null_ s is safe. Kotlin's type system protects us from getting _null pointer exceptions._

To get _null pointer exception_ you must do one of the following:

\- Explicitly throw _NullPointerException_

\- Use _!!_ operator (see examples we provided in this book)

\- Use Java code that is not guarded against it

\- Inconsistence with initialization

## Exceptions

To demonstrate _exceptions_ let's take a look at _Exceptions.kt_ :

class ExceptionExamples {

fun exceptionExmple() {

try {

// do something ...

} catch (e: KotlinNullPointerException) {

// handle exception

} finally {

// do something ...

}

}

__ // __ Try / Catch is expression!

fun exceptionExample2(): Int {

return try {

// do something

0

} catch (e: KotlinNullPointerException) {

// handle exception

-1

}

}

}

Kotlin doesn't have checked exceptions!

# Summary

In chapters and examples provided in Fundamental Kotlin book we were focused on very base usage of Kotlin programming language. The main goal was to demonstrate how to use it as a tool for a modern developer. There were no too deep theory chapters but short and clear code examples. More advanced topics (with more theory) and more advanced examples will be provided in next books that will be written.

Miloš Vasić,

Fall 2016.

# Literature

To write this book i used only official language specs and docs located on Kotlin programming language official website: <https://kotlinlang.org/>

Contents structure was also based on official Kotlin docs.

redpajama_set_name: RedPajamaBook


1935 House Bill 0993. An Act Relative To The Solicitation Of Fiduciary Positions And To The Unauthorized Practice Of Law.
Title 1935 House Bill 0993. An Act Relative To The Solicitation Of Fiduciary Positions And To The Unauthorized Practice Of Law.


text:
Q: How to write a JSON file into the dist folder by vue.config.js webpack config? The origin data is not from a file, but from a JSON object.
I already know how to use the native Node.js code to write a JSON file into the dist directory, but now I want to use vue.config.js webpack config to do this task.
I'm not familiar with webpack either. I simply checked some information, but I didn't find any way.
I hope to get some advice, thanks!

A: I found a solution.
const fs = require('fs-extra');

function JsonWebpackPlugin() {
  fs.writeJSONSync('./public/some.json', { a: 1 });
}
JsonWebpackPlugin.prototype.apply = new Function();

module.exports = {
    chainWebpack(config) {
        config.plugin('Json').use(JsonWebpackPlugin);
    }
}

redpajama_set_name: RedPajamaStackExchange


Do you want to get better lead to bodybuilding? Have you done some exercise yet never ever success? Well, perhaps you need some additional program. Besides visiting fitness program, taking in some supplements as well as great nutrition will complete your effort. Have you felt puzzled to get exactly what kind of supplement? Below it is the right Anavar with its professional item to develop your body healthily and flawlessly.
In this website, we have the best info about Coupon Code For Anavar In Canada . You might eat this product to help supplementing your body to develop considerably as well as get to the body shape as anticipated. The assumption could become a reality if you combine all initiatives. Well, the Anavar supplied in this internet site has excellent impact in order to help you realize the physical fitness program. Even there is some result happens due to this item, you could decrease it by regulation.
Are you still interested of this item? Locate the completed information by clicking and also seeing the main Anavar item site. You could shed all complication in order to question of this item. Yeah, when you speak with to the website, you can enhance exactly how the item will truly aid you to make much better intake. The site is likewise available to visit if you intend to acquire Anavar. Certainly, by acquiring the product, you can feel the actual impact.
Not any longer to await the product details! Only click and visit the official product to recognize exactly how the Anavar item will function. All details that we give in this site ideally will aid you to know more concerning all required for physical fitness program. You have to be creative to understand all information to create your body. When others really feel confused of the situation, you could get all information in this site. So, make sure that you will get the Anavar item and also give thanks to for it.
Anavar is an anabolic steroid belonging to the Dihydrotestosterone (DHT) household of anabolic steroid derivatives/analogues. Various other compounds that belong in this DHT household of anabolic steroids consist of Winstrol, Primobolan, Masteron, in addition to several others which are all by-products of the parent anabolic steroid DHT. The typical element amongst all of these anabolic steroids is that they are, in one way or another, changed forms of DHT and thus DHT could be taken into consideration the moms and dad hormone of these anabolic steroids. Anavar itself has a distinctive favor of anabolic stamina over its androgenic toughness (as seen by its anabolic ranking of 322 – 630 in light of its androgenic ranking of 24). In contrast with Testosterone, which has an anabolic: androgenic proportion of 100:100 specifically, it is quickly seen that Anavar is much much less androgenic and also possesses a stronger anabolic strength of a minimum of 3 times the stamina of Testosterone, and also researches have shown anabolic toughness as high as 6 times that of Testosterone with little associateding with androgenic activity. Anavar does not have any measurable estrogenic task (because of its nature of being a DHT derivative), neither does it hold any Progestogenic task.
It can be conveniently seen how these attributes make Anavar a favorable substance amongst athletes and also body builders desiring to increase athletic efficiency, muscular tissue gain, and strength gain where the additional water weight gain is undesired. It is also an anabolic steroid utilized extensively by body builders wanting to shed body fat as well as maintain as much muscular tissue as possible throughout a caloric deficit, where once again extra water weight as well as feasible fat retention/gain is not desired. As one may be able to quickly see, Anavar is quite a functional substance in regards to its usages. For an anabolic steroid typically proclaimed as being mild, it actually has some quite outstanding anabolic stamina as we can see from Anavars anabolic ranking of 322 – 630 versus Testosterones score of 100; and when as compared to the other preferred light anabolic steroid Primobolan, with its anabolic ranking of 88, we can see how Anavar is not as light in the sense of anabolic strength as several have made it out to be.
In relation to its reported anabolic ranking of 322 – 630, the reason that it is offered this array instead of one strong number for its anabolic rating (such as Trenbolones rating of a strong 500 or Testosterones ranking of a strong ONE HUNDRED) is due to Anavars nature as an oral anabolic steroid. It is comprehended that anabolic steroids display a quite bad percent of survivability via liver metabolic process when ingested by mouth. As we know that dental anabolic steroids are customized at the 17th carbon (known as C17 Alpha Alkylation) in order for the anabolic steroid to end up being more immune to break down in the liver, this grants a really high percent for anabolic steroids to go through the liver right into the bloodstream, however this does not make certain that 100% of the anabolic steroid makes it via. Some percent will still be unfortunately lost, and also as a result that is the reason instead of a solid number, a basic variety is offered for lots of anabolic steroids (mainly dental substances for the reasons specified, as strength could vary because of liver metabolic process).
For a very long time anavar was, and also still is, among the favored anabolic medications amongst women athletes for the terrific outcomes it brings and also its low androgenic task (which does not bring excess body and facial hair, deepening voice, and so on that steroids do offer). Moreover, it has actually been proven that oxandrolone helps to lower body fat in the stomach area, which, without doubts, is a wonderful bonus for ladies.
Even though its a moderate steroid, Anavar still has great effects on the human figure.
Muscle cells: Although tiny, the lean muscle mass which can be achieved from Anavar is still adequately for individuals to see and undoubtedly greater than can be acquired naturally.
Muscular tissue conservation: Among Anavars best residential properties is its capacity to maintain lean muscular tissue mass while on a reduced calorie diet.
Stacking advantages: Anavar makes a fantastic addition to steroids such as Trenbolone and Testosterone Propionate to form an excellent cutting cycle.
The best steroid for women: As mentioned over, because of its reduced androgenic properties, this steroid is the number 1 choice for ladies.
For physical fitness fanatics wanting to improve their look, helping their exercise as well as diet program is important. Anavar (also called Oxandrolone) is a light anabolic steroid that can help with precisely this kind of need. It doesn't have the exact same extreme side effects a much more effective steroid is understood to have, plus it can help with weight reduction and also muscular tissue manufacturing too.
Any person that desires improved muscle meaning and also size without obtaining large, puffy muscle mass, an Anavar just cycle is an excellent means to set about doing this. Nonetheless, it is essential to understand the medication further to obtain a better feeling on how it impacts the body.
The pharmacist behind the item is Searle Laboratories. Those not familiar with the name might acknowledge some of their items including Celebrex, NutraSweet and also Ambien. Searle Laboratories created Anavar to alleviate conditions of muscle mass losing as well as fast fat burning. In the muscle building neighborhood it is acknowledged as one of the safest anabolic steroids for males and females.
Oxandrolone is recognized for being light, having simply a minimal androgenic component to it. When used responsibly in advised doses it has actually shown to cause very few if any type of unfavorable side effects. Originally this steroid was established for usage in women and also children.
Utilizing Oxandrolone will certainly not cause stunted growth in kids since it wont close the epiphyseal growth layers too soon. Clinically speaking, Oxandrolone is commonly made use of to boost development in kids and also to stop the beginning of weakening of bones in ladies. It has actually ended up being preferred for female professional athletes because of its low risk of creating virilization symptoms to take place. The ideal as well as most safe dose for women seems to be an array of 10mg – 15mg a day.
Although moderate and also reduced in adverse effects, much more delicate customers or customers taking huge doses could still be at danger of particular adverse effects.
Nausea or vomiting, anorexia nervosa and lower in libido, although females normally find that Anavar creates an obvious boost in libido.
Acne and oily skin. This side effect is quite rare as well as opportunities of getting acne while on Anavar is tiny.
Similar to various other steroids, anavar could have an affect cholesterol degrees. It can rises the LDL cholesterol degrees (the bad cholesterol) and also lowers the level of HDL cholesterol (the good one).
It can trigger virilization problems in females, which once more, depends upon the quantity of drug consumed. This is why ladies take a reduced dosage as well as after that this negative effects is still feasible.
With the various steroids you are most likely to come across out there today, there is no other drug in the market which creates such curiosity. Anavar, because of the security requirements it has set, has more than the years obtained a huge follower complying with, be it those athletes or body builders planning to enhance their efficiency using this steroid or those planning to lower their weight quickly without having to go via strenuous gym schedules.
Anavar is readily available over-the-counter and also can likewise be purchased from the net without a prescription. It is additionally among the top vendors in the black market for those that planning to prevent the problems of undergoing a pharmacy. The underground market could demand you approximately $3.00 for a solitary tablet computer of Anavar, suggesting it is no affordable medication. The threat of purchasing medications like Anavar from dubious underground market dealerships is the fact that there is no warranty of authenticity. You may be handed some other drug packaged as Anavar and lose all your money. There's likewise the opportunity that the medication handed over to you could have been laced with habit forming agents or other steroids, the intake of which could possibly show to be a dreadful one for you at the end of it.
The authorities have to get this info out in the public regarding the ill-effects of acquiring controlled drugs from the black market. Those found guilty should not be let go free of charge as well as rigorous assents must be imposed on them. The authorities need to scrutinize every play being made by the black market and also respond appropriately. R & d organizations working with the development of Anavar, must be motivated and also provided with all the sources feasible so that they can make advances in their proposal making this medication beneficial to all.


text:
Um, Guys? It's Really Dark In Here...
by Alex V. Cook, Music Editor
first published: September, 2005
To me its the most elegant music devoid of schmaltz, and in many ways perfect.
(Southern Lord)
In an attempt to glean some wisdom and guidance in this endeavor as a music critic, and to stave off the boring stretches of powerlessness during the hurricane, I have been obsessively reading the latter Lester Bangs anthology "Main Lines, Blood Feasts and Bad Taste" and goddamn, he is such a great writer, even if he writes about the same dam,n thing all the time. If he'd gotten a nickel every time Iggy Pop or Lou Reed were mentioned, he could've paid that landlady always banging on his door in the background. But anyway, the wisdom. The subtext of Lester's writing is the increasing dehumanization of us all, and rock stars were about all we had left keeping us from gleefully getting the chips implanted and shuffling off to get our cafeteria trays filled with pablum. He did not buy into any infallibility of their actions, or cut them any moral slack like lovers of writers do (I mean, how can William Burroughs be a sanctioned thing when in practice, there is strong evidence that he was a child molester that shot his wife?) but he did allow for a new breed of rock star worship, one that looks to these innocent minions of dark forces to show us the way. Its like how in "Operation Manual for Spaceship Earth" Buckminster Fuller went into great detail explaining that the pirates were the last actualized men that controlled their sphere. For Lester, the insect distance in Lou Reed and the animal havoc of Iggy Pop were models for how to survive when the hammer comes down. For me, its the artists that create their own thing outside of the light. Make their own music how they want, start their own label, develop their own myths that are my models. To me Robin Hood would've been so much more successful had he not been such a glory hound.
My rock star worship has a wandering eye, and in the past couple years it has zeroed in on the likes of Jeff Tweedy, Julian Cope, Steve Albini, Lee Scratch Perry, all denizens of the alchemists lab, crafting magic off the radar (OK maybe not Tweedy, he's a big camera ho, but I love him anyway) and now my Cupid's arrow is aimed at the heart of Stephen O'Malley. Graphic designer by trade, his Southern Lord label which deals in the blackest of metal and reissues of lost classics is one of the best put-together outfits going. The album designs, especially the logos (a crucial part of metal) are impeccable, showing reverence to the classics of 80's logohood with a calligrapher's touch. His own band, Sunn O))), derived from the Sunn amps logo, even has such a typographically brilliant name that the logo actually appears in print. The image of them in the robes as druidic monks perfecting their own breed of sub-darkness through extreme means (which I'll get to in a moment) is awesome. And on top of all that floss and packaging and stuff I normally hate, the band kicks ass.
On Black One, the band pulls forms a wrecking crew of pulsar grade sub harmonics, where the guitar and bass and keyboards and whatever other eye of newt thrown in is reduced to a thick inky broth, flowing from your headphones like lava (I suggest headphones for the best Sunn O))) listening experience, unless you have some seriously good woofers on your hi-fi) engulfing your brain. The majority of the album is without percussion, just undulating pulses of bass distortion, interjected by a cast of Black Metal crooners giving their finest retching incantations. The first track "Sin Narvana" follows the live practice of Black Metal acts, of having an airy spooky instrumental track before kicking into the ritual killing, and this is a fine example of that sub-sub-genre, with its backward banshees spinning about what sound like the biggest didgeridoo in hell (and that is where all those didgeridoo players wind up). Where you might expect a 1-2-3-4 at the end of it, it opens up the funeral dirge of "It Took The Night To Believe" with locust-violin-guitars forming the elemental base while Wrest, throat scraper for Lurker of Chalice and Leviathan, bellows his cosmic dismay against the thunder. In fact, the climatology description become even more apparent in the nearly ambient "Cursed Realms (of the Winterdemons)" where the vocals are forced to strain against the winter and Gabriel's horn signalling the end. I might suggest a horn section on the next Sunn O))) outing, should they be looking for my input.
The album continues on this glacial tack, with a more obvious guitar riff (albeit slowed down to hypothermia levels) on "Orthodox Caveman" and a weirdly pretty piano echo running through "Cry For the Weeper" as a stampede of fuzz and power and vibration coming from the center of the universe. Here is the magic of Sunn O))) for me: They manage to combine effectively the rockstar egregiousness pushed to the logical conclusion that is inherent to Black Metal with an undeniable distillation of the sheer physicality of metal to its basest recognizable form. To me its the most elegant music devoid of schmaltz, and in many ways perfect.
The capper on this black iceberg is the 16 minute "Bathory Erzsebet" which contains upturns the BM tradition of the sadistic publicity stunt and photo shoot into reality. They took Malefic, the creative force behind my favorite BM studio project Xasthur, ensconced him in the robes, and then locked him in an actual coffin, set with microphone in the back of a rented hearse, and let the tape roll, giving some of the more chilling sonics available once Malefic's resolve starts to break down and begins (I'm assuming) losing his shit because he's locked in a coffin. The low hum provided by the group and the distortion on the vocals makes it hard to tell what is theatrical and what is real, and that is the shit. That's where the rock n roll rubber meets the conceptual road, pushing the tradition of Iggy rolling in glass and Jim Morrison wagging his weener at Miami onto the next, more dangerous stage of development. Once can assume that Malefic was in no actual harm here, but the harsh reality of it is nonetheless very real, despite what filters it is passing through. And therein lies the brilliance of this band and the reason for my idol worship of Stephen O'Malley and I bid you adieu as I let the final minutes of this CD joyously emulsify my soul into nothingness. See you in hell.
Alex V. Cook
Alex V. Cook listens to everything and writes about most of it. His latest book, the snappily titled Louisiana Saturday Night: Looking for a Good Time in South Louisiana's Juke Joints, Honky-Tonks, and Dance Halls is an odyssey from the backwoods bars and small-town dives to the swampside dance halls and converted clapboard barns of a Louisiana Saturday Night. Don't leave Heathrow without it. His first book Darkness Racket and Twang is available from SideCartel. The full effect can be had at alex v cook.com
about Alex V. Cook »»
Some Of Our Best Friends Are Songs: from Magnificent to Satie
50 songs we talked about in 2021...
The Book of Music, Alex V Cook's 'Darkness, Racket and Twang'
Outsideleft music editor, Alex V. Cook has just had his first book published by the SideCartel
Ten Dollar Trick
Chris Connolly trends towards the darkside, always. And Halloween is nearly here
The Black Michael Jackson
Joe Ambrose discovers the joys of portliness and the disappearance of the Black Michael Jackson
Todd Haynes: I'm Not There (Yet)
Outsideleft Goes To The Movies So You Won't Have To.
Marko Nyberg's Nordic Noir
John Robinson hears Marko Nyberg's new EP Ingrid

redpajama_set_name: RedPajamaCommonCrawl


text:
Mussoorie (Tibetan Homes)
SOS Children's Villages has been present in India since 1964 and has continued to grow ever since. In times of emergency, our organisation has responded with emergency relief programmes. In many cases, these developed into permanent programmes which offered support to the local people. At present SOS Children's Villages supports children, young people and families throughout India.
As people continue to arrive from Tibet, autonomous region of China, the pressure on resources grows
Education is taken very seriously by all (photo: SOS archives).
Tibetan Homes Foundation Mussoorie is located in the northern Indian state of Uttarakhand, about 35 kilometres from the state capital of Dehradun.
It is estimated that around 5,000 Tibetans live in Mussoorie. There are now two generations of Tibetans who have been born and brought up here. But people continue to arrive, especially after periods of unrest in Tibet. In addition children from Tibet are often sent to Mussoorie by their parents.
Mussoorie has become a tourist centre, attracting many visitors to the beautiful countryside and the cultural and religious sites. Tibetans have therefore found a way to make a living through servicing these visitors - they act as tourist guides or run restaurants, accommodation and shops. Others make carpets and other handicrafts which are primarily sold to visitors. Although tourism has provided people with a livelihood, it has also brought some environmental problems as the infrastructure struggles to deal with the increase in people.
Many educated young Tibetans face a hard choice: although they often want to remain in the Tibetan community, they find it hard to make a living here. In spite of efforts to create income-generating enterprises, the levels of unemployment remain high.
As a result, there are an increasing number of families who struggle to support themselves.
Supporting the children of Tibet, autonomous region of China
In 1962, the Tibetan Homes Foundation was established to provide care for Tibetan children. In 1962 a Tibetan Homes Foundation was set up in Mussoorie. As the children continued to arrive, this village could not accommodate them all, so a new village, named Mussoorie-Happy Valley was built right next door.
All the children in the families have lost parental care; while some children have no living parents, others have parents who are in Tibet, autonomous region of China in other locations throughout India, or further away.
What Tibetan Homes Foundation does in Mussoorie
Happy to have the chance to grow up in a loving home (photo: SOS archives).
Tibetan Homes Foundation Mussoorie provides day-care, medical and dental treatment, primary and secondary education, vocational training as well as family-based care.
Children who have lost parental care can live in one of the families alongside their brothers and sisters. Due to the great number of orphaned and abandoned children, families may have up to thirty members and sometimes even more. Young people live in special accommodation while they start vocational training or go on to higher education.
Children from the village and from surrounding families go to the Kindergarten. As the children grow older, the school allows them to receive primary and secondary education in accordance with their Tibetan beliefs.
There is also a Vocational Training Centre which offers courses in dress-making and arts and handicrafts, so that young people can generate an income in the future.