Roughly cover the materials in Chapters 1, 2, and 3.
## Install JetBrains IntelliJ
+ Visit [Official Website](https://www.jetbrains.com/idea/)
+ Community version is sufficient (and free)
+ Installation
1. Next

2. Next

3. Next

4. Install

5. Wait

6. Finish

+ Start IntelliJ
Press `Windows` button, then type `intellij` to find IntelliJ

## Kotlin Koans
+ A quick tutorial for Java developers.
## First Program
+ Create New Project

+ Choose Kotlin and put a proper name, then click "Create"

+ The project is ready
+ Compilation and execution
+ Click Run button

## Kotlin REPL
+ Read-Evaluate-Print Loop
+ Commonly Used Built-in Types
+ `String`: `"Hello"` `"World"`
+ `Char`: `'a'` `'b'`
+ `Boolean`: `true` `false`
+ `Int`: `123`
+ `Double`: `1.25`
+ Arithmatic Operations
+ `+` `-` `*` `/`
+ Remainder: `%`
## Variables
+ A variable in Kotlin is like a sticker on the box that stores the data.
+ Reference
+ Declaration
+ `var identifier: DataType = initialValue`
+ You may move the sticker to another box later.
+ `val identifier: DataType = initialValue`
+ You may **not** move the sticker to another box later.
+ Kotlin uses static type system. You may not change the data type of an identifier.
+ Type Inference: if the data type of `initialValue` is known, then you may omit `DataType`. For example: `var x = 5`
+ Assignment
+ `identifier = value`
+ `identifier = expression`
+ Read from the standard input
+ Add one line to import `java.util.Scanner`
+ `import java.util.Scanner`
+ Declair a `Scanner`-type variable to read from the standard input
+ ```val scanner = Scanner(System.`in`)```
+ Read a `String`: `scanner.next()`
+ Read an `Int`: `scanner.nextInt()`
+ Read a `Double`: `scanner.nextDouble()`
+ Read a `Boolean`: `scanner.nextBoolean()`
```kotlin=
import java.util.Scanner
fun main() {
val sc = Scanner(System.`in`)
print("Input an Int x: ")
var x = sc.nextInt()
println("x is $x")
println("x's square is ${x * x}")
print("Input a Double y: ")
val y = sc.nextDouble()
println("y is $y")
print("Input a String z: ")
var z = sc.next()
println("z is $z")
print("Input a Boolean: ")
var w = sc.nextBoolean()
println("w is $w")
}
```
+ Try the following statement in REPL
1. `var x: Int = 5`
2. `val y: String = "cat"`
3. `x = y`
+ This should cause an error: type mismatch
5. `y = "dog"`
+ You may not reassign a `val`
6. `val z = 9`
7. `x = z`
+ This is OK. `x` will be `9`
8. `z = x`
+ Again: not reassign a `val`
9. `x = x + 5`
+ This is OK. `x` will be `14`. $9+5$ is $14$.

+ Mutable versus immutable
+ Mutable: you may change the content in the box.
+ Immutable: you may **not** change the content in the box.
## Comment
+ ```
/* This is a multi-line comment.
Similar to C/C++/Java programming languages. */
```
+ ``` // This is a single-line comment.```
+ Add comments to make your code readable.
+ For you colleagues.
+ For the lecturer and the TAs.
+ For future yourselves.
## Conditions
+ Comparisons
+ `<`: Less than
+ `<=`: Less than or equal to
+ `>`: Greater than
+ `>=`: Greater than or equal to
+ Numbers: `Int` vs `Double`
+ `String` are compared by dictionary order.
+ `==`: Equal to
+ `!=`: Not equal to
+ Numbers: `Int` vs `Double`
+ `Double` are not accurate
+ `===`: Identical object
+ `!==`: Not identical object
+ Logical operators
+ `&&` : And
+ `||` : Or
+ `!`: Not
+ if/else statement
+ ```kotlin
if (booleanExpression) {
statementsForTrue
...
}
else { // optional
statementsForFalse
...
}
```
+ Example
```kotlin
import java.util.Scanner
fun main() {
val scanner = Scanner(System.`in`)
val x = 0 // scanner.nextInt()
if (x % 2 == 0) {
println("$x is even.")
}
else {
println("$x is odd.")
}
}
```
+ when
+ ```kotlin
when (expression) {
value1 -> {
statementsForValue1
}
value2 -> {
statementsForValue2
}
...
valueN -> {
statementsForValueN
}
else -> {
statementsForElse
}
}
```
+ Example
```kotlin
import java.util.Scanner
fun main() {
val scanner = Scanner(System.`in`)
val grade = "A" // scanner.next()
when (grade) {
"A" -> {
println("Good job!")
}
"B" -> {
println("Did you enjoy the course?")
}
"C" -> {
println("You still passed the course.")
}
else -> {
println("I'm sorry to hear that.")
}
}
}
```
+ ```kotlin
when {
expression1 -> {
statementsForExpression1
}
expression2 -> {
statementsForExpression2
}
...
expressionN -> {
statementsForExpressionN
}
else -> {
statementsForElse
}
}
```
+ Example
```kotlin
import java.util.Scanner
fun main() {
val scanner = Scanner(System.`in`)
val year = 2020 // scanner.nextInt()
when {
year % 400 == 0 -> {
println("$year is a leap year.")
}
year % 100 == 0 -> {
println("$year is not a leap year.")
}
year % 4 == 0 -> {
println("$year is a leap year.")
}
else -> {
println("$year is not a leap year.")
}
}
}
```
+ Practice: use "only one" if/else to re-implement the code above.
+ if/else expression
+ ```kotlin
import java.util.Scanner
fun main() {
val scanner = Scanner(System.`in`)
var x = 0 // scanner.nextInt()
val xIsEvenOrOdd = if (x % 2 == 0) "even" else "odd"
println(xIsEvenOrOdd)
}
```
+ when expression
+ ```kotlin
import java.util.Scanner
fun main() {
var day = "Saturday" // scanner.next()
val dayOfWeek = when (day) {
"Sunday" -> 0
"Monday" -> 1
"Tuesday" -> 2
"Wednesday" -> 3
"Thursday" -> 4
"Friday" -> 5
"Saturday" -> 6
else -> 777 // error code
}
println(dayOfWeek)
}
```
+ Score to grade example
```kotlin
import java.util.Scanner
fun main() {
val scanner = Scanner(System.`in`)
var score = 87 // scanner.nextInt()
val grade = when (score) {
0 -> "X"
in 90..100 -> "A+"
in 85..89 -> "A"
in 80..84 -> "A-"
in 77..79 -> "B+"
in 73..76 -> "B"
in 70..72 -> "B-"
in 67..69 -> "C+"
in 63..66 -> "C"
in 60..62 -> "C-"
in 50..59 -> "D"
in 1..49 -> "E"
else -> "Are you kidding me?" // error code
}
println(grade)
}
```
+ Nested statement
+ Both if/else statement and when statement are "statements".
+ They can be part of the statements between the braces `{` and `}`.
+ Like declarations, expressions, assignments.
+ Compound statement (Block)
```
{
statement1
statement2
...
statementN
}
```
+ ```kotlin
import java.util.Scanner
fun main() {
val scanner = Scanner(System.`in`)
println("Please input three integers separated by blanks:")
// Let the three integers be a, b, c.
val a = scanner.nextInt()
val b = scanner.nextInt()
val c = scanner.nextInt()
if (a <= b) { // a <= b <= c or a <= c <= b or c <= a <= b
when {
b <= c -> println("The order is: $a <= $b <= $c")
c <= a -> println("The order is: $c <= $a <= $b")
else -> // this can only be a <= c <= b
println("The order is: $a <= $c <= $b")
}
} else { // b <= a <= c or b <= c <= a or c <= b <= a
when {
a <= c -> println("The order is: $b <= $a <= $c")
c <= b -> println("The order is: $c <= $b <= $a")
else -> // this can only be b <= c <= a
println("The order is: $b <= $c <= $a")
}
}
}
```
## Loops and Ranges
+ while loop
+ ```kotlin
while (expression) {
statements // executed when expression == true
}
// stop looping if expression == false
```
+ ```kotlin
import java.util.Scanner
fun main() {
val scanner = Scanner(System.`in`)
print("Is TA handsome? ")
var isTAHandsome = scanner.next()
while (isTAHandsome != "Yes") {
print("Is TA handsome? ")
isTAHandsome = scanner.next()
}
println("You can pass now.") // TA is handsome.
}
```
+ do-while loop
+ ```kotlin
do {
statements
} while (expression)
// stop looping if expression == false
```
+ ```kotlin
import java.util.Scanner
fun main() {
val scanner = Scanner(System.`in`)
do {
print("Is TA handsome? ")
val isTAHandsome = scanner.next()
} while (isTAHandsome != "Yes")
println("You can pass now.") // TA is handsome.
}
```
+ ranges and progression
+ Assume `a`, `b`, `c` and `x` are all `Int`.
+ `a..b` : an `IntRange` represents $a,a+1,...,b$
+ `a..b step c`: an `IntProgression` represents $a,a+c,...,a+kc$ where $k=\left\lfloor\frac{b-a}{c}\right\rfloor$.
+ `a until b`: an `IntRange` represents $a,a+1,...,b-1$ (equivalent to `a..(b-1)`)
+ `a until b step c`: equivalent to `a..(b-1) step c`
+ `a downTo b`: an `IntProgression` represents $a,a-1,...,b$
+ `a downTo b step c`: an `IntProgression` represents $a,a-c,...,a-kc$ where $k=\left\lfloor\frac{a-b}{c}\right\rfloor$.
+ `in` operator
+ `x in a..b` is `true` if and only if `a <= x && x <= b`
+ `x in (a..b step c)` is `true` if and only if `x` is one of $a,a+c,...,a+kc$ where $k=\left\lfloor\frac{b-a}{c}\right\rfloor$.
+ for loop
+ ```kotlin
for (i in intProgression) {
// i will be assigned to next element in intProgression
statements
}
// end until every element in intProgression has been iterated
```
+ Example
```kotlin
fun main() {
for (i in 1..30 step 3) {
println(i)
}
}
```
+ continue
+ Skip the rest statements and start the next iteration
+ ```kotlin
fun main() {
for (i in 1..30 step 3) {
if (i % 2 == 0 || i % 5 == 0)
continue
println(i)
}
}
```
+ break
+ Terminate the loop immediately
+ ```kotlin
import java.util.Scanner
fun main() {
val scanner = Scanner(System.`in`)
print("Is TA handsome? ")
var isTAHandsome = scanner.next()
var inputTimes = 1
handsomeTA@while (isTAHandsome != "Yes") {
when (inputTimes) {
1 -> println("You cannot pass!")
2 -> println("You SHALL not pass!!")
else -> break@handsomeTA
}
print("Is TA handsome? ")
isTAHandsome = scanner.next()
inputTimes = inputTimes + 1
}
println("You can pass now.") // TA is nice.
}
```
+ `when` does not allow `break`/`continue` without label before Kotlin 1.4.
+ Label loop with `label@` and use `break@label`/`continue@label`
+ Can be used to `break`/`continue` multiple levels of loops.
## Practice Tasks
1. Write a program that reads three `Int` values, `a`, `b`, and `c` (separated by blanks), then prints the sum of integers in `a..b step c`.
2. Write a program that reads two decimal numbers $x$ and $y$ (separated by blanks) and prints $\frac{x}{y}$.
3. ```kotlin
import java.util.Scanner
fun main() {
val scanner = Scanner(System.`in`)
var command = scanner.next()
while (true) {
when (command) {
"ADD" -> {
val x = scanner.nextInt()
val y = scanner.nextInt()
println(x + y)
}
// More commands!
else ->
println("Unsupported command: " + command)
}
command = scanner.next()
}
}
```
Extend the above a REPL-style program to support the following commands:
+ `ADD x y`: print the value of $x+y$
+ `SUB x y`: print the value of $x-y$
+ `MUL x y`: print the value of $x\times y$
+ `DIV x y`: print the value of $\frac{x}{y}$ if $y\neq 0$, otherwise print `"DIVIDED by ZERO"`
+ `MOD x y`: print the value of `x % y` if $y\neq 0$, otherwise print `"DIVIDED by ZERO"`
+ `END`: terminate the program
Note the provided code will not terminate normally. Please make sure that your code will terminate by the `END` command.
## References
+ [Basic Types](https://kotlinlang.org/docs/reference/basic-types.html)
+ [Control Flow](https://kotlinlang.org/docs/reference/control-flow.html)
## More Excercises for Beginners
+ Try to google (or any other search engine) things like [this](http://www.beginwithjava.com/java/loops/questions.html).