Kotlin in Action : Chapter 2, Kotlin Basics

Caren Chang
3 min readApr 23, 2017

--

Continuing my reading of Kotlin in Action, Chapter 2 summarizes the basic usages of the Kotlin programming language.

(Check out summaries of other chapters al listed here : https://medium.com/@calren24/reading-through-kotlin-in-action-428111b051ce)

Basic structure of a Kotlin function

  • declare function with fun keyword
  • parameter type comes after its name
  • function can be declared at top level of file, doesn’t need to be in class
  • no ending semicolon

Statements vs Expressions

An expression has a value (so it can be used as part of another expression), while a statement is a top-level element in its enclosing block and doesn’t have it’s own value. Kotlin uses expressions more ubiquitously, thus helping make it less verbose than Java. In the example code block from above, you can see the if statement being used as an expression.

Expression Bodies

  • thanks to type inference, the function above can be further simplified to be:
fun max(a: Int, b: Int) = if (a > b) a else b

Variables in Kotlin

val answer = 42 // Kotlin can infer the variable is an Int

Variable keywords in kotlin:

val (immutable reference) = Java’s final

var (mutable reference) = Java’s regular non-final variable

// Kotlin
val answer = 42
// Java equivalent
final int answer = 42;

String templates in Kotlin:

fun main(args: Array<String>) {
val name = if (args.size > 0) args[0] else “Kotlin"
println(“Hello, $name!”)
}
// will print "Hello Kotlin" if no arguments are given, or "Hello
// Ash" if Ash is the given argument
  • Like Java’s string concatenation, but automatically uses a string builder!

Classes

/* Java */public class Person {
private final String name;
private boolean isMarried;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}

public boolean isMarried() {
return isMarried;
}
public void setIsMarried(boolean isMarried) {
this.isMarried = isMarried;
}
}
/* Kotlin */
class Person(
val name: String, // read only, has field and getter
var isMarried: Boolean // writable, has field, getter, setter
)
  • In the example below, isSquare doesn’t need a field to store its value, instead it has a custom getter that we implemented
class Rectangle(val height: Int, val width: Int) {
val isSquare: Boolean
get() {
return height == width
}
}
  • you can import a function from another package by name
import geometry.shapes.createRandomRectangle
// createRandomRectangle is a function

Enums and “when” in Kotlin

  • Kotlin’s “when” is like Java’s “switch”, but it’s more powerful because you can use more than just enum, strings or number constants
// in this example of an enum class in Kotlin, you can declare 
// specific properties and functions in the enum class
enum class Color(
val r: Int, val g: Int, val b: Int
) {
RED(255, 0, 0), ORANGE(255, 165, 0),
YELLOW(255, 255, 0), GREEN(0, 255, 0),
BLUE(0, 0, 255), INDIGO(75, 0, 130),
VIOLET(238, 130, 238);
fun rgb() = (r * 256 + g) * 256 + b
}
  • the “when” clause can take more than one argument
fun mix(c1: Color, c2: Color) =
when (setOf(c1, c2)) {
setOf(RED, YELLOW) -> ORANGE
setOf(YELLOW, BLUE) -> GREEN
setOf(BLUE, VIOLET) -> INDIGO
else -> throw Exception(“Weird color”)
}

Smart casting

  • you don’t have to cast a variable after checking it’s type
if (t is TreeNode) {
return e.right + e.left
}
// we can call e.right and e.left without casting it as a TreeNode

Iterating

  • Kotlin and Java have the same while loop structure, and Kotlin’s for loop is like Java’s for-each loop
// prints number from 1 through 10
for (i in 1 ... 10) {
print(i)
}
// prints 100, 98, 96 ...
for (i in 100 downTo 1 step 2) {
print(i)
}

Exception Handling

  • exception handling in Kotlin is similar to that in Java, except Kotlin doesn’t differentiate between checked and unchecked exceptions
fun readNumber(reader: BufferedReader) {
val number = try {
Integer.parseInt(reader.readLine())
} catch (e: NumberFormatException) {
null
}
println(number)
}
// in this example you can opt to catch the NumberFormatException, // but you aren't forced to catch the IOException

Chapter 1: What and Why
Chapter 3: Calling and Defining Functions

--

--