Introduction
Hello World
package org.kotlinlang.play // 1
fun main() { // 2
println("Hello, World!") // 3
}
- Kotlin code is usually defined in packages. Package specification is optional: If you don't specify a package in a source file, its content goes to the default package.
- An entry point to a Kotlin application is the
main
function. You can declare it without any parameters. The return type is not specified, which means that the function returns nothing. println
writes a line to the standard output. It is imported implicitly. Also, note that semicolons at the end of code lines are optional.
Functions
Default Parameter Values and Named Arguments
fun printMessage(message: String): Unit { // 1
println(message)
}
fun printMessageWithPrefix(message: String, prefix: String = "Info") { // 2
println("[$prefix] $message")
}
fun sum(x: Int, y: Int): Int { // 3
return x + y
}
fun multiply(x: Int, y: Int) = x * y // 4
fun main() {
printMessage("Hello") // 5
printMessageWithPrefix("Hello", "Log") // 6
printMessageWithPrefix("Hello") // 7
printMessageWithPrefix(prefix = "Log", message = "Hello") // 8
println(sum(1, 2)) // 9
println(multiply(2, 4)) // 10
}
- A simple function that takes a parameter of type
String
and returnsUnit
(i.e., no return value). - A function that takes a second optional parameter with default value
Info
. The return type is omitted, meaning that it's actuallyUnit
. - A function that returns an integer.
- A single-expression function that returns an integer (inferred).
- Calls the first function with the argument
Hello
. - Calls the function with two parameters, passing values for both of them.
- Calls the same function omitting the second one. The default value
Info
is used. - Calls the same function using named arguments and changing the order of the arguments.
- Prints the result of the
sum
function call. - Prints the result of the
multiply
function call.
Infix Functions
Member functions and extensions with a single parameter can be turned into infix functions.
fun main() {
infix fun Int.times(str: String) = str.repeat(this) // 1
println(2 times "Bye ") // 2
val pair = "Ferrari" to "Katrina" // 3
println(pair)
infix fun String.onto(other: String) = Pair(this, other) // 4
val myPair = "McLaren" onto "Lucas"
println(myPair)
val sophia = Person("Sophia")
val claudia = Person("Claudia")
sophia likes claudia // 5
}
class Person(val name: String) {
val likedPeople = mutableListOf<Person>()
infix fun likes(other: Person) { likedPeople.add(other) } // 6
}
- Defines an infix extension function on
Int
. - Calls the infix function.
- Creates a
Pair
by calling the infix functionto
from the standard library. - Here's your own implementation of
to
creatively calledonto
. - Infix notation also works on members functions (methods).
- The containing class becomes the first parameter.
Note that the example uses local functions (functions nested within another function).
Operator Functions
Certain functions can be "upgraded" to operators, allowing their calls with the corresponding operator symbol.
fun main() {
operator fun Int.times(str: String) = str.repeat(this) // 1
println(2 * "Bye ") // 2
operator fun String.get(range: IntRange) = substring(range) // 3
val str = "Always forgive your enemies; nothing annoys them so much."
println(str[0..14]) // 4
}
- This takes the infix function from above one step further using the
operator
modifier. - The operator symbol for
times()
is*
so that you can call the function using2 * "Bye"
. - An operator function allows easy range access on strings.
- The
get()
operator enables bracket-access syntax.
Functions with vararg
Parameters
Varargs allow you to pass any number of arguments by separating them with commas.
fun main() {
fun printAll(vararg messages: String) { // 1
for (m in messages) println(m)
}
printAll("Hello", "Hallo", "Salut", "Hola", "你好") // 2
fun printAllWithPrefix(vararg messages: String, prefix: String) { // 3
for (m in messages) println(prefix + m)
}
printAllWithPrefix(
"Hello", "Hallo", "Salut", "Hola", "你好",
prefix = "Greeting: " // 4
)
fun log(vararg entries: String) {
printAll(*entries) // 5
}
log("Hello", "Hallo", "Salut", "Hola", "你好")
}
- The
vararg
modifier turns a parameter into a vararg. - This allows calling
printAll
with any number of string arguments. - Thanks to named parameters, you can even add another parameter of the same type after the vararg. This wouldn't be allowed in Java because there's no way to pass a value.
- Using named parameters, you can set a value to
prefix
separately from the vararg. - At runtime, a vararg is just an array. To pass it along into a vararg parameter, use the special spread operator
*
that lets you pass in*entries
(a vararg ofString
) instead ofentries
(anArray<String>
).
Variables
Kotlin has powerful type inference. While you can explicitly declare the type of a variable, you'll usually let the compiler do the work by inferring it. Kotlin does not enforce immutability, though it is recommended. In essence use val over var.
fun main() {
var a: String = "initial" // 1
println(a)
val b: Int = 1 // 2
val c = 3 // 3
}
- Declares a mutable variable and initializes it.
- Declares an immutable variable and initializes it.
- Declares an immutable variable and initializes it without specifying the type. The compiler infers the type
Int
.
fun main() {
var e: Int // 1
println(e) // 2
}
{validate="false"}
- Declares a variable without initialization.
- An attempt to use the variable causes a compiler error:
Variable 'e' must be initialized
.
You're free to choose when you initialize a variable, however, it must be initialized before the first read.
fun someCondition() = true
fun main() {
val d: Int // 1
if (someCondition()) {
d = 1 // 2
} else {
d = 2 // 2
}
println(d) // 3
}
- Declares a variable without initialization.
- Initializes the variable with different values depending on some condition.
- Reading the variable is possible because it's already been initialized.
Null Safety
In an effort to rid the world of NullPointerException
, variable types in Kotlin don't allow the assignment of null
. If you need a variable that can be null, declare it nullable by adding ?
at the end of its type.
fun main() {
var neverNull: String = "This can't be null" // 1
neverNull = null // 2
var nullable: String? = "You can keep a null here" // 3
nullable = null // 4
var inferredNonNull = "The compiler assumes non-null" // 5
inferredNonNull = null // 6
fun strLength(notNull: String): Int { // 7
return notNull.length
}
strLength(neverNull) // 8
strLength(nullable) // 9
}
{validate="false"}
- Declares a non-
null
String variable. - When trying to assign
null
to non-nullable variable, a compilation error is produced. - Declares a nullable String variable.
- Sets the
null
value to the nullable variable. This is OK. - When inferring types, the compiler assumes non-
null
for variables that are initialized with a value. - When trying to assign
null
to a variable with inferred type, a compilation error is produced. - Declares a function with a non-
null
string parameter. - Calls the function with a
String
(non-nullable) argument. This is OK. - When calling the function with a
String?
(nullable) argument, a compilation error is produced.
Working with Nulls
Sometimes Kotlin programs need to work with null values, such as when interacting with external Java code or representing a truly absent state. Kotlin provides null tracking to elegantly deal with such situations.
fun describeString(maybeString: String?): String { // 1
if (maybeString != null && maybeString.length > 0) { // 2
return "String of length ${maybeString.length}"
} else {
return "Empty or null string" // 3
}
}
fun main() {
println(describeString(null))
}
- A function that takes in a nullable string and returns its description.
- If the given string is not
null
and not empty, return information about its length. - Otherwise, tell the caller that the string is empty or null.
Classes
The class declaration consists of the class name, the class header (specifying its type parameters, the primary constructor etc.) and the class body, surrounded by curly braces. Both the header and the body are optional; if the class has no body, curly braces can be omitted.
class Customer // 1
class Contact(val id: Int, var email: String) // 2
fun main() {
val customer = Customer() // 3
val contact = Contact(1, "mary@gmail.com") // 4
println(contact.id) // 5
contact.email = "jane@gmail.com" // 6
}
- Declares a class named
Customer
without any properties or user-defined constructors. A non-parameterized default constructor is created by Kotlin automatically. - Declares a class with two properties: immutable
id
and mutableemail
, and a constructor with two parametersid
andemail
. - Creates an instance of the class
Customer
via the default constructor. Note that there is nonew
keyword in Kotlin. - Creates an instance of the class
Contact
using the constructor with two arguments. - Accesses the property
id
. - Updates the value of the property
email
.
Generics
Generics are a genericity mechanism that's become standard in modern languages. Generic classes and functions increase code reusability by encapsulating common logic that is independent of a particular generic type, like the logic inside a List<T>
is independent of what T
is.
Generic Classes
The first way to use generics in Kotlin is creating generic classes.
class MutableStack<E>(vararg items: E) { // 1
private val elements = items.toMutableList()
fun push(element: E) = elements.add(element) // 2
fun peek(): E = elements.last() // 3
fun pop(): E = elements.removeAt(elements.size - 1)
fun isEmpty() = elements.isEmpty()
fun size() = elements.size
override fun toString() = "MutableStack(${elements.joinToString()})"
}
fun main() {
val stack = MutableStack(0.62, 3.14, 2.7)
stack.push(9.87)
println(stack)
println("peek(): ${stack.peek()}")
println(stack)
for (i in 1..stack.size()) {
println("pop(): ${stack.pop()}")
println(stack)
}
}
- Defines a generic class
MutableStack<E>
whereE
is called the generic type parameter. At use-site, it is assigned to a specific type such asInt
by declaring aMutableStack<Int>
. - Inside the generic class,
E
can be used as a parameter like any other type. - You can also use
E
as a return type.
Note that the implementation makes heavy use of Kotlin's shorthand syntax for functions that can be defined in a single expression.
Generic Functions
You can also generify functions if their logic is independent of a specific type. For instance, you can write a utility function to create mutable stacks:
class MutableStack<E>(vararg items: E) { // 1
private val elements = items.toMutableList()
fun push(element: E) = elements.add(element) // 2
fun peek(): E = elements.last() // 3
fun pop(): E = elements.removeAt(elements.size - 1)
fun isEmpty() = elements.isEmpty()
fun size() = elements.size
override fun toString() = "MutableStack(${elements.joinToString()})"
}
fun <E> mutableStackOf(vararg elements: E) = MutableStack(*elements)
fun main() {
val stack = mutableStackOf(0.62, 3.14, 2.7)
println(stack)
}
Note that the compiler can infer the generic type from the parameters of mutableStackOf
so that you don't have to write mutableStackOf<Double>(...)
.
Inheritance
Kotlin fully supports the traditional object-oriented inheritance mechanism.
open class Dog { // 1
open fun sayHello() { // 2
println("wow wow!")
}
}
class Yorkshire : Dog() { // 3
override fun sayHello() { // 4
println("wif wif!")
}
}
fun main() {
val dog: Dog = Yorkshire()
dog.sayHello()
}
- Kotlin classes are final by default. If you want to allow the class inheritance, mark the class with the
open
modifier. - Kotlin methods are also final by default. As with the classes, the
open
modifier allows overriding them. - A class inherits a superclass when you specify the
: SuperclassName()
after its name. The empty parentheses()
indicate an invocation of the superclass default constructor. - Overriding methods or attributes requires the
override
modifier.
Inheritance with Parameterized Constructor
open class Tiger(val origin: String) {
fun sayHello() {
println("A tiger from $origin says: grrhhh!")
}
}
class SiberianTiger : Tiger("Siberia") // 1
fun main() {
val tiger: Tiger = SiberianTiger()
tiger.sayHello()
}
- If you want to use a parameterized constructor of the superclass when creating a subclass, provide the constructor arguments in the subclass declaration.
Passing Constructor Arguments to Superclass
open class Lion(val name: String, val origin: String) {
fun sayHello() {
println("$name, the lion from $origin says: graoh!")
}
}
class Asiatic(name: String) : Lion(name = name, origin = "India") // 1
fun main() {
val lion: Lion = Asiatic("Rufo") // 2
lion.sayHello()
}
name
in theAsiatic
declaration is neither avar
norval
: it's a constructor argument, whose value is passed to thename
property of the superclassLion
.- Creates an
Asiatic
instance with the nameRufo
. The call invokes theLion
constructor with argumentsRufo
andIndia
.
Control Flow
When
Instead of the widely used switch
statement, Kotlin provides the more flexible and clear when
construction. It can be used either as a statement or as an expression.
When Statement
fun main() {
cases("Hello")
cases(1)
cases(0L)
cases(MyClass())
cases("hello")
}
fun cases(obj: Any) {
when (obj) { // 1
1 -> println("One") // 2
"Hello" -> println("Greeting") // 3
is Long -> println("Long") // 4
!is String -> println("Not a string") // 5
else -> println("Unknown") // 6
}
}
class MyClass
- This is a
when
statement. - Checks whether
obj
equals to1
. - Checks whether
obj
equals to"Hello"
. - Performs type checking.
- Performs inverse type checking.
- Default statement (might be omitted).
Note that all branch conditions are checked sequentially until one of them is satisfied. So, only the first suitable branch will be executed.
When Expression
fun main() {
println(whenAssign("Hello"))
println(whenAssign(3.4))
println(whenAssign(1))
println(whenAssign(MyClass()))
}
fun whenAssign(obj: Any): Any {
val result = when (obj) { // 1
1 -> "one" // 2
"Hello" -> 1 // 3
is Long -> false // 4
else -> 42 // 5
}
return result
}
class MyClass
- This is a
when
expression. - Sets the value to
"one"
ifobj
equals to1
. - Sets the value to one if
obj
equals to"Hello"
. - Sets the value to
false
ifobj
is an instance ofLong
. - Sets the value
42
if none of the previous conditions are satisfied. Unlike inwhen
statement, the default branch is usually required inwhen
expression, except the case when the compiler can check that other branches cover all possible cases.
Loops
Kotlin supports all the commonly used loops: for
, while
, do-while
for
for
in Kotlin works the same way as in most languages.
fun main(args: Array<String>) {
val cakes = listOf("carrot", "cheese", "chocolate")
for (cake in cakes) { // 1
println("Yummy, it's a $cake cake!")
}
}
- Loops through each cake in the list.
while
and do-while
while
and do-while
constructs work similarly to most languages as well.
fun eatACake() = println("Eat a Cake")
fun bakeACake() = println("Bake a Cake")
fun main(args: Array<String>) {
var cakesEaten = 0
var cakesBaked = 0
while (cakesEaten < 5) { // 1
eatACake()
cakesEaten ++
}
do { // 2
bakeACake()
cakesBaked++
} while (cakesBaked < cakesEaten)
}
- Executes the block while the condition is true.
- Executes the block first and then checking the condition.
Iterators
You can define your own iterators in your classes by implementing the iterator
operator in them.
class Animal(val name: String)
class Zoo(val animals: List<Animal>) {
operator fun iterator(): Iterator<Animal> { // 1
return animals.iterator() // 2
}
}
fun main() {
val zoo = Zoo(listOf(Animal("zebra"), Animal("lion")))
for (animal in zoo) { // 3
println("Watch out, it's a ${animal.name}")
}
}
- Defines an iterator in a class. It must be named
iterator
and have theoperator
modifier. - Returns the iterator that meets the following method requirements:
next()
:Animal
hasNext()
:Boolean
- Loops through animals in the zoo with the user-defined iterator.
The iterator can be declared in the type or as an extension function.
Ranges
There is a set of tools for defining ranges in Kotlin. Let's have a brief look at them.
fun main() {
for(i in 0..3) { // 1
print(i)
}
print(" ")
for(i in 0 until 3) { // 2
print(i)
}
print(" ")
for(i in 2..8 step 2) { // 3
print(i)
}
print(" ")
for (i in 3 downTo 0) { // 4
print(i)
}
print(" ")
}
- Iterates over a range starting from 0 up to 3 (inclusive). Like 'for(i=0; i<=3; ++i)' in other programming languages (C/C++/Java).
- Iterates over a range starting from 0 up to 3 (exclusive). Like for loop in Python or like 'for(i=0; i<3; ++i)' in other programming languages (C/C++/Java).
- Iterates over a range with a custom increment step for consecutive elements.
- Iterates over a range in reverse order.
Char ranges are also supported:
fun main() {
for (c in 'a'..'d') { // 1
print(c)
}
print(" ")
for (c in 'z' downTo 's' step 2) { // 2
print(c)
}
print(" ")
}
- Iterates over a char range in alphabetical order.
- Char ranges support
step
anddownTo
as well.
Ranges are also useful in if
statements:
fun main() {
val x = 2
if (x in 1..5) { // 1
print("x is in range from 1 to 5")
}
println()
if (x !in 6..10) { // 2
print("x is not in range from 6 to 10")
}
}
- Checks if a value is in the range.
!in
is the opposite ofin
.
Equality Checks
Kotlin uses ==
for structural comparison and ===
for referential comparison.
More precisely, a == b
compiles down to if (a == null) b == null else a.equals(b)
.
fun main() {
val authors = setOf("Shakespeare", "Hemingway", "Twain")
val writers = setOf("Twain", "Shakespeare", "Hemingway")
println(authors == writers) // 1
println(authors === writers) // 2
}
- Returns
true
because it callsauthors.equals(writers)
and sets ignore element order. - Returns
false
becauseauthors
andwriters
are distinct references.
Conditional Expression
There is no ternary operator condition ? then : else
in Kotlin. Instead, if
may be used as an expression:
fun main() {
fun max(a: Int, b: Int) = if (a > b) a else b // 1
println(max(99, -42))
}
if
is an expression here: it returns a value.
Special Classes
Data Classes
Data classes make it easy to create classes that are used to store values. Such classes are automatically provided with methods for copying, getting a string representation, and using instances in collections. You can override these methods with your own implementations in the class declaration.
data class User(val name: String, val id: Int) { // 1
override fun equals(other: Any?) =
other is User && other.id == this.id // 2
}
fun main() {
val user = User("Alex", 1)
println(user) // 3
val secondUser = User("Alex", 1)
val thirdUser = User("Max", 2)
println("user == secondUser: ${user == secondUser}") // 4
println("user == thirdUser: ${user == thirdUser}")
// hashCode() function
println(user.hashCode()) // 5
println(secondUser.hashCode())
println(thirdUser.hashCode())
// copy() function
println(user.copy()) // 6
println(user === user.copy()) // 7
println(user.copy("Max")) // 8
println(user.copy(id = 3)) // 9
println("name = ${user.component1()}") // 10
println("id = ${user.component2()}")
}
- Defines a data class with the
data
modifier. - Override the default
equals
method by declaring users equal if they have the sameid
. - Method
toString
is auto-generated, which makesprintln
output look nice. - Our custom
equals
considers two instances equal if theirid
s are equal. - Data class instances with exactly matching attributes have the same
hashCode
. - Auto-generated
copy
function makes it easy to create a new instance. copy
creates a new instance, so the object and its copy have distinct references.- When copying, you can change values of certain properties.
copy
accepts arguments in the same order as the class constructor. - Use
copy
with named arguments to change the value despite of the properties order. - Auto-generated
componentN
functions let you get the values of properties in the order of declaration.
Enum Classes
Enum classes are used to model types that represent a finite set of distinct values, such as directions, states, modes, and so forth.
enum class State {
IDLE, RUNNING, FINISHED // 1
}
fun main() {
val state = State.RUNNING // 2
val message = when (state) { // 3
State.IDLE -> "It's idle"
State.RUNNING -> "It's running"
State.FINISHED -> "It's finished"
}
println(message)
}
- Defines a simple enum class with three enum constants. The number of constants is always finite and they are all distinct.
- Accesses an enum constant via the class name.
- With enums, the compiler can infer if a
when
-expression is exhaustive so that you don't need theelse
-case.
Enums may contain properties and methods like other classes, separated from the list of enum constants by a semicolon.
enum class Color(val rgb: Int) { // 1
RED(0xFF0000), // 2
GREEN(0x00FF00),
BLUE(0x0000FF),
YELLOW(0xFFFF00);
fun containsRed() = (this.rgb and 0xFF0000 != 0) // 3
}
fun main() {
val red = Color.RED
println(red) // 4
println(red.containsRed()) // 5
println(Color.BLUE.containsRed()) // 6
println(Color.YELLOW.containsRed()) // 7
}
- Defines an enum class with a property and a method.
- Each enum constant must pass an argument for the constructor parameter.
- Enum class members are separated from the constant definitions by a semicolon.
- The default
toString
returns the name of the constant, here"RED"
. - Calls a method on an enum constant.
- Calls a method via enum class name.
- The RGB values of
RED
andYELLOW
share first bits (FF
) so this prints 'true'.
Sealed Classes
Sealed classes let you restrict the use of inheritance. Once you declare a class sealed, it can only be subclassed from inside the same package where the sealed class is declared. It cannot be subclassed outside of the package where the sealed class is declared.
sealed class Mammal(val name: String) // 1
class Cat(val catName: String) : Mammal(catName) // 2
class Human(val humanName: String, val job: String) : Mammal(humanName)
fun greetMammal(mammal: Mammal): String {
when (mammal) { // 3
is Human -> return "Hello ${mammal.name}; You're working as a ${mammal.job}" // 4
is Cat -> return "Hello ${mammal.name}" // 5
} // 6
}
fun main() {
println(greetMammal(Cat("Snowy")))
}
- Defines a sealed class.
- Defines subclasses. Note that all subclasses must be in the same package.
- Uses an instance of the sealed class as an argument in a
when
expression. - A smartcast is performed, casting
Mammal
toHuman
. - A smartcast is performed, casting
Mammal
toCat
. - The
else
-case is not necessary here since all possible subclasses of the sealed class are covered. With a non-sealed superclasselse
would be required.
Object Keyword
Classes and objects in Kotlin work the same way as in most object-oriented languages: a class is a blueprint, and an object is an instance of a class. Usually, you define a class and then create multiple instances of that class:
import java.util.Random
class LuckDispatcher { //1
fun getNumber() { //2
var objRandom = Random()
println(objRandom.nextInt(90))
}
}
fun main() {
val d1 = LuckDispatcher() //3
val d2 = LuckDispatcher()
d1.getNumber() //4
d2.getNumber()
}
- Defines a blueprint.
- Defines a method.
- Creates instances.
- Calls the method on instances.
In Kotlin you also have the object keyword. It is used to obtain a data type with a single implementation.
If you are a Java user and want to understand what "single" means, you can think of the Singleton pattern: it ensures you that only one instance of that class is created even if 2 threads try to create it.
To achieve this in Kotlin, you only need to declare an object
: no class, no constructor, only a lazy instance.
Why lazy? Because it will be created once when the object is accessed. Otherwise, it won't even be created.
object
Expression
Here is a basic typical usage of an object
expression: a simple object/properties structure.
There is no need to do so in class declaration: you create a single object, declare its members and access it within one function.
Objects like this are often created in Java as anonymous class instances.
fun rentPrice(standardDays: Int, festivityDays: Int, specialDays: Int): Unit { //1
val dayRates = object { //2
var standard: Int = 30 * standardDays
var festivity: Int = 50 * festivityDays
var special: Int = 100 * specialDays
}
val total = dayRates.standard + dayRates.festivity + dayRates.special //3
print("Total price: $$total") //4
}
fun main() {
rentPrice(10, 2, 1) //5
}
- Creates a function with parameters.
- Creates an object to use when calculating the result value.
- Accesses the object's properties.
- Prints the result.
- Calls the function. This is when the object is actually created.
object
Declaration
You can also use the object
declaration. It isn't an expression, and can't be used in a variable assignment. You should use it to directly access its members:
object DoAuth { //1
fun takeParams(username: String, password: String) { //2
println("input Auth parameters = $username:$password")
}
}
fun main(){
DoAuth.takeParams("foo", "qwerty") //3
}
- Creates an object declaration.
- Defines the object method.
- Calls the method. This is when the object is actually created.
Companion Objects
An object declaration inside a class defines another useful case: the companion object. Syntactically it's similar to the static methods in Java: you call object members using its class name as a qualifier. If you plan to use a companion object in Kotlin, consider using a package-level function instead.
class BigBen { //1
companion object Bonger { //2
fun getBongs(nTimes: Int) { //3
for (i in 1 .. nTimes) {
print("BONG ")
}
}
}
}
fun main() {
BigBen.getBongs(12) //4
}
- Defines a class.
- Defines a companion. Its name can be omitted.
- Defines a companion object method.
- Calls the companion object method via the class name.
Functional
Higher-Order Functions
A higher-order function is a function that takes another function as parameter and/or returns a function.
Taking Functions as Parameters
fun calculate(x: Int, y: Int, operation: (Int, Int) -> Int): Int { // 1
return operation(x, y) // 2
}
fun sum(x: Int, y: Int) = x + y // 3
fun main() {
val sumResult = calculate(4, 5, ::sum) // 4
val mulResult = calculate(4, 5) { a, b -> a * b } // 5
println("sumResult $sumResult, mulResult $mulResult")
}
- Declares a higher-order function. It takes two integer parameters,
x
andy
. Additionally, it takes another functionoperation
as a parameter. Theoperation
parameters and return type are also defined in the declaration. - The higher order function returns the result of
operation
invocation with the supplied arguments. - Declares a function that matches the
operation
signature. - Invokes the higher-order function passing in two integer values and the function argument
::sum
.::
is the notation that references a function by name in Kotlin. - Invokes the higher-order function passing in a lambda as a function argument. Looks clearer, doesn't it?
Returning Functions
fun operation(): (Int) -> Int { // 1
return ::square
}
fun square(x: Int) = x * x // 2
fun main() {
val func = operation() // 3
println(func(2)) // 4
}
- Declares a higher-order function that returns a function.
(Int) -> Int
represents the parameters and return type of thesquare
function. - Declares a function matching the signature.
- Invokes
operation
to get the result assigned to a variable. Herefunc
becomessquare
which is returned byoperation
. - Invokes
func
. Thesquare
function is actually executed.
Lambda Functions
Lambda functions ("lambdas") are a simple way to create functions ad-hoc. Lambdas can be denoted very concisely in many cases thanks to type inference and the implicit it
variable.
fun main() {
// All examples create a function object that performs upper-casing.
// So it's a function from String to String
val upperCase1: (String) -> String = { str: String -> str.uppercase() } // 1
val upperCase2: (String) -> String = { str -> str.uppercase() } // 2
val upperCase3 = { str: String -> str.uppercase() } // 3
// val upperCase4 = { str -> str.uppercase() } // 4
val upperCase5: (String) -> String = { it.uppercase() } // 5
val upperCase6: (String) -> String = String::uppercase // 6
println(upperCase1("hello"))
println(upperCase2("hello"))
println(upperCase3("hello"))
println(upperCase5("hello"))
println(upperCase6("hello"))
}
- A lambda in all its glory, with explicit types everywhere. The lambda is the part in curly braces, which is assigned to a variable of type
(String) -> String
(a function type). - Type inference inside lambda: the type of the lambda parameter is inferred from the type of the variable it's assigned to.
- Type inference outside lambda: the type of the variable is inferred from the type of the lambda parameter and return value.
- You cannot do both together, the compiler has no chance to infer the type that way.
- For lambdas with a single parameter, you don't have to explicitly name it. Instead, you can use the implicit
it
variable. This is especially useful when the type ofit
can be inferred (which is often the case). - If your lambda consists of a single function call, you may use function pointers (
::
) .
Extension Functions and Properties
Kotlin lets you add new members to any class with the extensions mechanism. Namely, there are two types of extensions: extension functions and extension properties. They look a lot like normal functions and properties but with one important difference: you need to specify the type that you extend.
data class Item(val name: String, val price: Float) // 1
data class Order(val items: Collection<Item>)
fun Order.maxPricedItemValue(): Float = this.items.maxByOrNull { it.price }?.price ?: 0F // 2
fun Order.maxPricedItemName() = this.items.maxByOrNull { it.price }?.name ?: "NO_PRODUCTS"
val Order.commaDelimitedItemNames: String // 3
get() = items.map { it.name }.joinToString()
fun main() {
val order = Order(listOf(Item("Bread", 25.0F), Item("Wine", 29.0F), Item("Water", 12.0F)))
println("Max priced item name: ${order.maxPricedItemName()}") // 4
println("Max priced item value: ${order.maxPricedItemValue()}")
println("Items: ${order.commaDelimitedItemNames}") // 5
}
- Defines simple models of
Item
andOrder
.Order
can contain a collection ofItem
objects. - Adds extension functions for the
Order
type. - Adds an extension property for the
Order
type. - Calls extension functions directly on an instance of
Order
. - Accesses the extension property on an instance of
Order
.
It is even possible to execute extensions on null
references. In an extension function, you can check the object for null
and use the result in your code:
fun <T> T?.nullSafeToString() = this?.toString() ?: "NULL" // 1
fun main() {
println(null.nullSafeToString())
println("Kotlin".nullSafeToString())
}
Collections
List
A list is an ordered collection of items. In Kotlin, lists can be either mutable (MutableList
) or read-only (List
). For list creation, use the standard library functions listOf()
for read-only lists and mutableListOf()
for mutable lists. To prevent unwanted modifications, obtain read-only views of mutable lists by casting them to List
.
val systemUsers: MutableList<Int> = mutableListOf(1, 2, 3) // 1
val sudoers: List<Int> = systemUsers // 2
fun addSystemUser(newUser: Int) { // 3
systemUsers.add(newUser)
}
fun getSysSudoers(): List<Int> { // 4
return sudoers
}
fun main() {
addSystemUser(4) // 5
println("Tot sudoers: ${getSysSudoers().size}") // 6
getSysSudoers().forEach { // 7
i -> println("Some useful info on user $i")
}
// getSysSudoers().add(5) <- Error! // 8
}
- Creates a
MutableList
. - Creates a read-only view of the list.
- Adds a new item to the
MutableList
. - A function that returns an immutable
List
. - Updates the
MutableList
. All related read-only views are updated as well since they point to the same object. - Retrieves the size of the read-only list.
- Iterates the list and prints its elements.
- Attempting to write to the read-only view causes a compilation error.
Set
A set is an unordered collection that does not support duplicates. For creating sets, there are functions setOf()
and mutableSetOf()
. A read-only view of a mutable set can be obtained by casting it to Set
.
val openIssues: MutableSet<String> = mutableSetOf("uniqueDescr1", "uniqueDescr2", "uniqueDescr3") // 1
fun addIssue(uniqueDesc: String): Boolean {
return openIssues.add(uniqueDesc) // 2
}
fun getStatusLog(isAdded: Boolean): String {
return if (isAdded) "registered correctly." else "marked as duplicate and rejected." // 3
}
fun main() {
val aNewIssue: String = "uniqueDescr4"
val anIssueAlreadyIn: String = "uniqueDescr2"
println("Issue $aNewIssue ${getStatusLog(addIssue(aNewIssue))}") // 4
println("Issue $anIssueAlreadyIn ${getStatusLog(addIssue(anIssueAlreadyIn))}") // 5
}
- Creates a
Set
with given elements. - Returns a boolean value showing if the element was actually added.
- Returns a string, based on function input parameter.
- Prints a success message: the new element is added to the
Set
. - Prints a failure message: the element can't be added because it duplicates an existing element.
Map
A map is a collection of key/value pairs, where each key is unique and is used to retrieve the corresponding value. For creating maps, there are functions mapOf()
and mutableMapOf()
. Using the to infix function makes initialization less noisy. A read-only view of a mutable map can be obtained by casting it to Map
.
const val POINTS_X_PASS: Int = 15
val EZPassAccounts: MutableMap<Int, Int> = mutableMapOf(1 to 100, 2 to 100, 3 to 100) // 1
val EZPassReport: Map<Int, Int> = EZPassAccounts // 2
fun updatePointsCredit(accountId: Int) {
if (EZPassAccounts.containsKey(accountId)) { // 3
println("Updating $accountId...")
EZPassAccounts[accountId] = EZPassAccounts.getValue(accountId) + POINTS_X_PASS // 4
} else {
println("Error: Trying to update a non-existing account (id: $accountId)")
}
}
fun accountsReport() {
println("EZ-Pass report:")
EZPassReport.forEach { // 5
k, v -> println("ID $k: credit $v")
}
}
fun main() {
accountsReport() // 6
updatePointsCredit(1) // 7
updatePointsCredit(1)
updatePointsCredit(5) // 8
accountsReport() // 9
}
- Creates a mutable
Map
. - Creates a read-only view of the
Map
. - Checks if the
Map
's key exists. - Reads the corresponding value and increments it with a constant value.
- Iterates immutable
Map
and prints key/value pairs. - Reads the account points balance, before updates.
- Updates an existing account two times.
- Tries to update a non-existing account: prints an error message.
- Reads the account points balance, after updates.
filter
filter function enables you to filter collections. It takes a filter predicate as a lambda-parameter. The predicate is applied to each element. Elements that make the predicate true
are returned in the result collection.
fun main() {
val numbers = listOf(1, -2, 3, -4, 5, -6) // 1
val positives = numbers.filter { x -> x > 0 } // 2
val negatives = numbers.filter { it < 0 } // 3
println("Numbers: $numbers")
println("Positive Numbers: $positives")
println("Negative Numbers: $negatives")
}
- Defines collection of numbers.
- Gets positive numbers.
- Uses the shorter
it
notation to get negative numbers.
map
map extension function enables you to apply a transformation to all elements in a collection. It takes a transformer function as a lambda-parameter.
fun main() {
val numbers = listOf(1, -2, 3, -4, 5, -6) // 1
val doubled = numbers.map { x -> x * 2 } // 2
val tripled = numbers.map { it * 3 } // 3
println("Numbers: $numbers")
println("Doubled Numbers: $doubled")
println("Tripled Numbers: $tripled")
}
- Defines a collection of numbers.
- Doubles numbers.
- Uses the shorter
it
notation to triple the numbers.
any, all, none
These functions check the existence of collection elements that match a given predicate.
Function any
Function any
returns true
if the collection contains at least one element that matches the given predicate.
fun main() {
val numbers = listOf(1, -2, 3, -4, 5, -6) // 1
val anyNegative = numbers.any { it < 0 } // 2
val anyGT6 = numbers.any { it > 6 } // 3
println("Numbers: $numbers")
println("Is there any number less than 0: $anyNegative")
println("Is there any number greater than 6: $anyGT6")
}
- Defines a collection of numbers.
- Checks if there are negative elements.
- Checks if there are elements greater than
6
.
Function all
Function all
returns true
if all elements in collection match the given predicate.
fun main() {
val numbers = listOf(1, -2, 3, -4, 5, -6) // 1
val allEven = numbers.all { it % 2 == 0 } // 2
val allLess6 = numbers.all { it < 6 } // 3
println("Numbers: $numbers")
println("All numbers are even: $allEven")
println("All numbers are less than 6: $allLess6")
}
- Defines a collection of numbers.
- Checks whether all elements are even.
- Checks whether all elements are less than
6
.
Function none
Function none
returns true
if there are no elements that match the given predicate in the collection.
fun main() {
val numbers = listOf(1, -2, 3, -4, 5, -6) // 1
val allEven = numbers.none { it % 2 == 1 } // 2
val allLess6 = numbers.none { it > 6 } // 3
println("Numbers: $numbers")
println("All numbers are even: $allEven")
println("No element greater than 6: $allLess6")
}
- Defines a collection of numbers.
- Checks if there are no odd elements (all elements are even).
- Checks if there are no elements greater than 6.
find, findLast
The find
and findLast
functions return the first or the last collection element that matches the given predicate. If there are no such elements, these functions return null
.
fun main() {
val words = listOf("Lets", "find", "something", "in", "collection", "somehow") // 1
val first = words.find { it.startsWith("some") } // 2
val last = words.findLast { it.startsWith("some") } // 3
val nothing = words.find { it.contains("nothing") } // 4
println("The first word starting with \"some\" is \"$first\"")
println("The last word starting with \"some\" is \"$last\"")
println("The first word containing \"nothing\" is ${nothing?.let { "\"$it\"" } ?: "null"}")
}
- Defines a collection of words.
- Looks for the first word starting with "some".
- Looks for the last word starting with "some".
- Looks for the first word containing "nothing".
first, last
first
, last
These functions return the first and the last element of the collection correspondingly. You can also use them with a predicate; in this case, they return the first or the last element that matches the given predicate.
If a collection is empty or doesn't contain elements matching the predicate, the functions throw NoSuchElementException
.
fun main() {
val numbers = listOf(1, -2, 3, -4, 5, -6) // 1
val first = numbers.first() // 2
val last = numbers.last() // 3
val firstEven = numbers.first { it % 2 == 0 } // 4
val lastOdd = numbers.last { it % 2 != 0 } // 5
println("Numbers: $numbers")
println("First $first, last $last, first even $firstEven, last odd $lastOdd")
}
- Defines a collection of numbers.
- Picks the first element.
- Picks the last element.
- Picks the first even element.
- Picks the last odd element.
firstOrNull
, lastOrNull
These functions work almost the same way with one difference: they return null
if there are no matching elements.
fun main() {
val words = listOf("foo", "bar", "baz", "faz") // 1
val empty = emptyList<String>() // 2
val first = empty.firstOrNull() // 3
val last = empty.lastOrNull() // 4
val firstF = words.firstOrNull { it.startsWith('f') } // 5
val firstZ = words.firstOrNull { it.startsWith('z') } // 6
val lastF = words.lastOrNull { it.endsWith('f') } // 7
val lastZ = words.lastOrNull { it.endsWith('z') } // 8
println("Empty list: first is $first, last is $last")
println("Word list: first item starting with 'f' is $firstF, first item starting with 'z' is $firstZ")
println("Word list: last item ending with 'f' is $lastF, last item ending with 'z' is $lastZ")
}
- Defines a collection of words.
- Defines an empty collection.
- Picks the first element from empty collection. It supposed to be
null
. - Picks the last element from empty collection. It supposed to be
null
as well. - Picks the first word starting with 'f'.
- Picks the first word starting with 'z'.
- Picks the last word ending with 'f'.
- Picks the last word ending with 'z'.
count
count
functions returns either the total number of elements in a collection or the number of elements matching the given predicate.
fun main() {
val numbers = listOf(1, -2, 3, -4, 5, -6) // 1
val totalCount = numbers.count() // 2
val evenCount = numbers.count { it % 2 == 0 } // 3
println("Total number of elements: $totalCount")
println("Number of even elements: $evenCount")
}
- Defines a collection of numbers.
- Counts the total number of elements.
- Counts the number of even elements.
associateBy, groupBy
Functions associateBy
and groupBy
build maps from the elements of a collection indexed by the specified key. The key is defined in the keySelector
parameter.
You can also specify an optional valueSelector
to define what will be stored in the value
of the map element.
The difference between associateBy
and groupBy
is how they process objects with the same key:
associateBy
uses the last suitable element as the value.groupBy
builds a list of all suitable elements and puts it in the value.
The returned map preserves the entry iteration order of the original collection.
fun main() {
data class Person(val name: String, val city: String, val phone: String) // 1
val people = listOf( // 2
Person("John", "Boston", "+1-888-123456"),
Person("Sarah", "Munich", "+49-777-789123"),
Person("Svyatoslav", "Saint-Petersburg", "+7-999-456789"),
Person("Vasilisa", "Saint-Petersburg", "+7-999-123456"))
val phoneBook = people.associateBy { it.phone } // 3
val cityBook = people.associateBy(Person::phone, Person::city) // 4
val peopleCities = people.groupBy(Person::city, Person::name) // 5
val lastPersonCity = people.associateBy(Person::city, Person::name) // 6
println("People: $people")
println("Phone book: $phoneBook")
println("City book: $cityBook")
println("People living in each city: $peopleCities")
println("Last person living in each city: $lastPersonCity")
}
- Defines a data class that describes a person.
- Defines a collection of people.
- Builds a map from phone numbers to their owners' information.
it.phone
is thekeySelector
here. ThevalueSelector
is not provided, so the values of the map arePerson
objects themselves. - Builds a map from phone numbers to the cities where owners live.
Person::city
is thevalueSelector
here, so the values of the map contain only cities. - Builds a map that contains cities and people living there. The values of the map are lists of person names.
- Builds a map that contains cities and the last person living there. The values of the map are names of the last person living in each city.
partition
The partition
function splits the original collection into a pair of lists using a given predicate:
- Elements for which the predicate is
true
. - Elements for which the predicate is
false
.
fun main() {
val numbers = listOf(1, -2, 3, -4, 5, -6) // 1
val evenOdd = numbers.partition { it % 2 == 0 } // 2
val (positives, negatives) = numbers.partition { it > 0 } // 3
println("Numbers: $numbers")
println("Even numbers: ${evenOdd.first}")
println("Odd numbers: ${evenOdd.second}")
println("Positive numbers: $positives")
println("Negative numbers: $negatives")
}
- Defines a collection of numbers.
- Splits
numbers
into aPair
of lists with even and odd numbers. - Splits
numbers
into two lists with positive and negative numbers. Pair destructuring is applied here to get thePair
members.
flatMap
flatMap
transforms each element of a collection into an iterable object and builds a single list of the transformation results. The transformation is user-defined.
fun main() {
val fruitsBag = listOf("apple","orange","banana","grapes") // 1
val clothesBag = listOf("shirts","pants","jeans") // 2
val cart = listOf(fruitsBag, clothesBag) // 3
val mapBag = cart.map { it } // 4
val flatMapBag = cart.flatMap { it } // 5
println("Your bags are: $mapBag")
println("The things you bought are: $flatMapBag")
}
- Defines a collection of Strings with fruit names.
- Defines a collection of Strings with clothes names.
- Adds
fruitsBag
andclothesBag
to thecart
list. - Builds a
map
ofcart
elements, which is a list of two lists. - Builds a
flatMap
ofcart
elements, which is a single list consisting of elements from both lists.
minOrNull, maxOrNull
minOrNull
and maxOrNull
functions return the smallest and the largest element of a collection. If the collection is empty, they return null
.
fun main() {
val numbers = listOf(1, 2, 3)
val empty = emptyList<Int>()
val only = listOf(3)
println("Numbers: $numbers, min = ${numbers.minOrNull()} max = ${numbers.maxOrNull()}") // 1
println("Empty: $empty, min = ${empty.minOrNull()}, max = ${empty.maxOrNull()}") // 2
println("Only: $only, min = ${only.minOrNull()}, max = ${only.maxOrNull()}") // 3
}
- For non-empty collection, functions return the smallest and the largest element.
- For empty collections, both functions return
null
. - For collection with only one element, both functions return the same value.
sorted
sorted
returns a list of collection elements sorted according to their natural sort order (ascending).
sortedBy
sorts elements according to natural sort order of the values returned by specified selector function.
import kotlin.math.abs
fun main() {
val shuffled = listOf(5, 4, 2, 1, 3, -10) // 1
val natural = shuffled.sorted() // 2
val inverted = shuffled.sortedBy { -it } // 3
val descending = shuffled.sortedDescending() // 4
val descendingBy = shuffled.sortedByDescending { abs(it) } // 5
println("Shuffled: $shuffled")
println("Natural order: $natural")
println("Inverted natural order: $inverted")
println("Inverted natural order value: $descending")
println("Inverted natural order of absolute values: $descendingBy")
}
- Defines a collection of shuffled numbers.
- Sorts it in the natural order.
- Sorts it in the inverted natural order by using
-it
as a selector function. - Sorts it in the inverted natural order by using
sortedDescending
. - Sorts it in the inverted natural order of items' absolute values by using
abs(it)
as a selector function.
Map Element Access
When applied to a map, []
operator returns the value corresponding to the given key, or null
if there is no such key in the map.
getValue
function returns an existing value corresponding to the given key or throws an exception if the key wasn't found.
For maps created with withDefault
, getValue
returns the default value instead of throwing an exception.
fun main(args: Array<String>) {
val map = mapOf("key" to 42)
val value1 = map["key"] // 1
val value2 = map["key2"] // 2
val value3: Int = map.getValue("key") // 1
val mapWithDefault = map.withDefault { k -> k.length }
val value4 = mapWithDefault.getValue("key2") // 3
try {
map.getValue("anotherKey") // 4
} catch (e: NoSuchElementException) {
println("Message: $e")
}
println("value1 is $value1")
println("value2 is $value2")
println("value3 is $value3")
println("value4 is $value4")
}
- Returns 42 because it's the value corresponding to the key
"key"
. - Returns
null
because"key2"
is not in the map. - Returns the default value because
"key2"
is absent. For this key it's 4. - Throws
NoSuchElementException
because"anotherKey"
is not in the map.
zip
zip
function merges two given collections into a new collection. By default, the result collection contains Pairs
of source collection elements with the same index. However, you can define your own structure of the result collection element.
The size of the result collection equals to the minimum size of a source collection.
fun main() {
val A = listOf("a", "b", "c") // 1
val B = listOf(1, 2, 3, 4) // 1
val resultPairs = A zip B // 2
val resultReduce = A.zip(B) { a, b -> "$a$b" } // 3
println("A to B: $resultPairs")
println("\$A\$B: $resultReduce")
}
- Defines two collections.
- Merges them into a list of pairs. The infix notation is used here.
- Merges them into a list of String values by the given transformation.
getOrElse
getOrElse
provides safe access to elements of a collection. It takes an index and a function that provides the default value
in cases when the index is out of bound.
fun main() {
val list = listOf(0, 10, 20)
println(list.getOrElse(1) { 42 }) // 1
println(list.getOrElse(10) { 42 }) // 2
}
- Prints the element at the index
1
. - Prints
42
because the index10
is out of bounds.
getOrElse
can also be applied to Map
to get the value for the given key.
fun main() {
val map = mutableMapOf<String, Int?>()
println(map.getOrElse("x") { 1 }) // 1
map["x"] = 3
println(map.getOrElse("x") { 1 }) // 2
map["x"] = null
println(map.getOrElse("x") { 1 }) // 3
}
- Prints the default value because the key
"x"
is not in the map. - Prints
3
, the value for the key"x"
. - Prints the default value because the value for the key
"x"
is not defined.
Scope Functions
let
The Kotlin standard library function let
can be used for scoping and null-checks. When called on an object, let
executes the given block of code and returns the result of its last expression.
The object is accessible inside the block by the reference it
(by default) or a custom name.
fun customPrint(s: String) {
print(s.uppercase())
}
fun main() {
val empty = "test".let { // 1
customPrint(it) // 2
it.isEmpty() // 3
}
println(" is empty: $empty")
fun printNonNull(str: String?) {
println("Printing \"$str\":")
str?.let { // 4
print("\t")
customPrint(it)
println()
}
}
fun printIfBothNonNull(strOne: String?, strTwo: String?) {
strOne?.let { firstString -> // 5
strTwo?.let { secondString ->
customPrint("$firstString : $secondString")
println()
}
}
}
printNonNull(null)
printNonNull("my string")
printIfBothNonNull("First","Second")
}
- Calls the given block on the result on the string "test".
- Calls the function on "test" by the
it
reference. let
returns the value of this expression.- Uses safe call, so
let
and its code block will be executed only on non-null values. - Uses the custom name instead of
it
, so that the nestedlet
can access the context object of the outerlet
.
run
Like let
, run
is another scoping function from the standard library. Basically, it does the same: executes a code block and returns its result.
The difference is that inside run
the object is accessed by this
. This is useful when you want to call the object's methods rather than pass it as an argument.
fun main() {
fun getNullableLength(ns: String?) {
println("for \"$ns\":")
ns?.run { // 1
println("\tis empty? " + isEmpty()) // 2
println("\tlength = $length")
length // 3
}
}
getNullableLength(null)
getNullableLength("")
getNullableLength("some string with Kotlin")
}
- Calls the given block on a nullable variable.
- Inside
run
, the object's members are accessed without its name. run
returns thelength
of the givenString
if it's notnull
.
with
with
is a non-extension function that can access members of its argument concisely: you can omit the instance name when referring to its members.
class Configuration(var host: String, var port: Int)
fun main() {
val configuration = Configuration(host = "127.0.0.1", port = 9000)
with(configuration) {
println("$host:$port")
}
// instead of:
println("${configuration.host}:${configuration.port}")
}
apply
apply
executes a block of code on an object and returns the object itself. Inside the block, the object is referenced by this
.
This function is handy for initializing objects.
data class Person(var name: String, var age: Int, var about: String) {
constructor() : this("", 0, "")
}
fun main() {
val jake = Person() // 1
val stringDescription = jake.apply { // 2
name = "Jake" // 3
age = 30
about = "Android developer"
}.toString() // 4
println(stringDescription)
}
- Creates a
Person()
instance with default property values. - Applies the code block (next 3 lines) to the instance.
- Inside
apply
, it's equivalent tojake.name = "Jake"
. - The return value is the instance itself, so you can chain other operations.
also
also
works like apply
: it executes a given block and returns the object called.
Inside the block, the object is referenced by it
, so it's easier to pass it as an argument.
This function is handy for embedding additional actions, such as logging in call chains.
data class Person(var name: String, var age: Int, var about: String) {
constructor() : this("", 0, "")
}
fun writeCreationLog(p: Person) {
println("A new person ${p.name} was created.")
}
fun main() {
val jake = Person("Jake", 30, "Android developer") // 1
.also { // 2
writeCreationLog(it) // 3
}
}
- Creates a
Person()
object with the given property values. - Applies the given code block to the object. The return value is the object itself.
- Calls the logging function passing the object as an argument.
Delegation
Delegation Pattern
Kotlin supports easy implementation of the delegation pattern on the native level without any boilerplate code.
interface SoundBehavior { // 1
fun makeSound()
}
class ScreamBehavior(val n: String): SoundBehavior { // 2
override fun makeSound() = println("${n.uppercase()} !!!")
}
class RockAndRollBehavior(val n: String): SoundBehavior { // 2
override fun makeSound() = println("I'm The King of Rock 'N' Roll: $n")
}
// Tom Araya is the "singer" of Slayer
class TomAraya(n: String): SoundBehavior by ScreamBehavior(n) // 3
// You should know ;)
class ElvisPresley(n: String): SoundBehavior by RockAndRollBehavior(n) // 3
fun main() {
val tomAraya = TomAraya("Thrash Metal")
tomAraya.makeSound() // 4
val elvisPresley = ElvisPresley("Dancin' to the Jailhouse Rock.")
elvisPresley.makeSound()
}
- Defines the interface
SoundBehavior
with one method. - The classes
ScreamBehavior
andRockAndRollBehavior
implement the interface and contain their own implementations of the method. - The classes
TomAraya
andElvisPresley
also implement the interface, but not the method. Instead, they delegate the method calls to the responsible implementation. The delegate object is defined after theby
keyword. As you see, no boilerplate code is required. - When
makeSound()
is called ontomAraya
of typeTomAraya
orelvisPresley
of typeElvisPresley
, the call is delegated to the corresponding delegate object.
Delegated Properties
Kotlin provides a mechanism of delegated properties that allows delegating the calls of the property set
and get
methods to a certain object.
The delegate object in this case should have the method getValue
. For mutable properties, you'll also need setValue
.
import kotlin.reflect.KProperty
class Example {
var p: String by Delegate() // 1
override fun toString() = "Example Class"
}
class Delegate() {
operator fun getValue(thisRef: Any?, prop: KProperty<*>): String { // 2
return "$thisRef, thank you for delegating '${prop.name}' to me!"
}
operator fun setValue(thisRef: Any?, prop: KProperty<*>, value: String) { // 2
println("$value has been assigned to ${prop.name} in $thisRef")
}
}
fun main() {
val e = Example()
println(e.p)
e.p = "NEW"
}
- Delegates property
p
of typeString
to the instance of classDelegate
. The delegate object is defined after theby
keyword. - Delegation methods. The signatures of these methods are always as shown in the example. Implementations may contain any steps you need. For immutable properties only
getValue
is required.
Standard Delegates
The Kotlin standard library contains a bunch of useful delegates, like lazy
, observable
, and others. You may use them as is.
For example lazy
is used for lazy initialization.
class LazySample {
init {
println("created!") // 1
}
val lazyStr: String by lazy {
println("computed!") // 2
"my lazy"
}
}
fun main() {
val sample = LazySample() // 1
println("lazyStr = ${sample.lazyStr}") // 2
println(" = ${sample.lazyStr}") // 3
}
- Property
lazy
is not initialized on object creation. - The first call to
get()
executes the lambda expression passed tolazy()
as an argument and saves the result. - Further calls to
get()
return the saved result.
If you want thread safety, use blockingLazy()
instead: it guarantees that the values will be computed only in one thread and that all threads will see the same value.
Storing Properties in a Map
Property delegation can be used for storing properties in a map. This is handy for tasks like parsing JSON or doing other "dynamic" stuff.
class User(val map: Map<String, Any?>) {
val name: String by map // 1
val age: Int by map // 1
}
fun main() {
val user = User(mapOf(
"name" to "John Doe",
"age" to 25
))
println("name = ${user.name}, age = ${user.age}")
}
- Delegates take values from the
map
by the string keys - names of properties.
You can delegate mutable properties to a map as well. In this case, the map will be modified upon property assignments. Note that you will need MutableMap
instead of read-only Map
.
Productivity Boosters
Named Arguments
As with most other programming languages (Java, C++, etc.), Kotlin supports passing arguments to methods and constructors according to the order they are defined. Kotlin also supports named arguments to allow clearer invocations and avoid mistakes with the order of arguments. Such mistakes are hard to find because they are not detected by the compiler, for example, when two sequential arguments have the same type.
fun format(userName: String, domain: String) = "$userName@$domain"
fun main() {
println(format("mario", "example.com")) // 1
println(format("domain.com", "username")) // 2
println(format(userName = "foo", domain = "bar.com")) // 3
println(format(domain = "frog.com", userName = "pepe")) // 4
}
- Calls a function with argument values.
- Calls a function with switched arguments. No syntax errors, but the result domain.com@username is incorrect.
- Calls a function with named arguments.
- When invoking a function with named arguments, you can specify them in any order you like.
String Templates
String templates allow you to include variable references and expressions into strings. When the value of a string is requested (for example, by println
), all references and expressions are substituted with actual values.
fun main() {
val greeting = "Kotliner"
println("Hello $greeting") // 1
println("Hello ${greeting.uppercase()}") // 2
}
- Prints a string with a variable reference. References in strings start with
$
. - Prints a string with an expression. Expressions start with
$
and are enclosed in curly braces.
Destructuring Declarations
Destructuring declaration syntax can be very handy, especially when you need an instance only for accessing its members. It lets you define the instance without a specific name therefore saving a few lines of code.
fun findMinMax(list: List<Int>): Pair<Int, Int> {
// do the math
return Pair(50, 100)
}
fun main() {
val (x, y, z) = arrayOf(5, 10, 15) // 1
val map = mapOf("Alice" to 21, "Bob" to 25)
for ((name, age) in map) { // 2
println("$name is $age years old")
}
val (min, max) = findMinMax(listOf(100, 90, 50, 98, 76, 83)) // 3
}
- Destructures an
Array
. The number of variables on the left side matches the number of arguments on the right side. - Maps can be destructured as well.
name
andage
variables are mapped to the map key and value. - Built-in
Pair
andTriple
types support destructuring too, even as return values from functions.
data class User(val username: String, val email: String) // 1
fun getUser() = User("Mary", "mary@somewhere.com")
fun main() {
val user = getUser()
val (username, email) = user // 2
println(username == user.component1()) // 3
val (_, emailAddress) = getUser() // 4
}
- Defines a data class.
- Destructures an instance. Declared values are mapped to the instance fields.
- Data class automatically defines the
component1()
andcomponent2()
methods that will be called during destructuring. - Use underscore if you don't need one of the values, avoiding the compiler hint indicating an unused variable.
class Pair<K, V>(val first: K, val second: V) { // 1
operator fun component1(): K {
return first
}
operator fun component2(): V {
return second
}
}
fun main() {
val (num, name) = Pair(1, "one") // 2
println("num = $num, name = $name")
}
- Defines a custom
Pair
class withcomponent1()
andcomponent2()
methods. - Destructures an instance of this class the same way as for built-in
Pair
.
Smart Casts
The Kotlin compiler is smart enough to perform type casts automatically in most cases, including:
- Casts from nullable types to their non-nullable counterparts.
- Casts from a supertype to a subtype.
import java.time.LocalDate
import java.time.chrono.ChronoLocalDate
fun main() {
val date: ChronoLocalDate? = LocalDate.now() // 1
if (date != null) {
println(date.isLeapYear) // 2
}
if (date != null && date.isLeapYear) { // 3
println("It's a leap year!")
}
if (date == null || !date.isLeapYear) { // 4
println("There's no Feb 29 this year...")
}
if (date is LocalDate) {
val month = date.monthValue // 5
println(month)
}
}
- Declares a nullable variable.
- Smart-cast to non-nullable (thus allowing direct access to
isLeapYear
). - Smart-cast inside a condition (this is possible because, like Java, Kotlin uses short-circuiting).
- Smart-cast inside a condition (also enabled by short-circuiting).
- Smart-cast to the subtype
LocalDate
.
This way, you can automatically use variables as desired in most cases without doing obvious casts manually.
Kotlin/JS
dynamic
dynamic is a special type in Kotlin/JS. It basically turns off Kotlin's type checker. That is needed in order to interoperate with untyped or loosely typed environments, such as the JavaScript ecosystem.
fun main(){
val a: dynamic = "abc" // 1
val b: String = a // 2
fun firstChar(s: String) = s[0]
println("${firstChar(a)} == ${firstChar(b)}") // 3
println("${a.charCodeAt(0, "dummy argument")} == ${b[0].toInt()}") // 4
println(a.charAt(1).repeat(3)) // 5
fun plus(v: dynamic) = v + 2
println("2 + 2 = ${plus(2)}") // 6
println("'2' + 2 = ${plus("2")}")
}
- Any value can be assigned to a
dynamic
variable type. - A dynamic value can be assigned to anything.
- A dynamic variable can be passed as an argument to any function.
- Any property or function with any arguments can be called on a
dynamic
variable. - A function call on a
dynamic
variable always returns a dynamic value, so it is possible to chain the calls. - Operators, assignments, and indexed access (
[..]
) are translated "as is". Beware!
JS function
You can inline JavaScript code into your Kotlin code using the js("…") function. This should be used with extreme care.
fun main() {
js("alert(\"alert from Kotlin!\")") // 1
}
- Sending a JavaScript alert from a Kotlin function.
fun main(){
val json = js("{}") // 1
json.name = "Jane" // 2
json.hobby = "movies"
println(JSON.stringify(json)) // 3
}
- Creates a JavaScript object literal. The
js(...)
function return type isdynamic
. - Adds some properties by utilizing the
dynamic
type capabilities. - Passes the JSON to JavaScript API.
External declarations
external keyword allows to declare existing JavaScript API in a type-safe way.
external fun alert(msg: String) // 1
fun main() {
alert("Hi!") // 2
}
- Declares an existing JavaScript function
alert
which takes a singleString
argument. - Uses
alert
as if it were regular Kotlin.
Note that Kotlin checks during compilation, that a single argument of type String is passed. Such a check prevents some bugs even when using pure JavaScript API.
Please refer to the docs in order to learn more about describing existing JavaScript API.
Canvas (Hello Kotlin)
The following example demonstrates usage of HTML5 Canvas from Kotlin.
Here strange creatures are watching the kotlin logo. You can drag'n'drop them as well as the logo. Doubleclick to add more creatures but be careful. They may be watching you!
package creatures
import org.w3c.dom.*
import org.w3c.dom.events.MouseEvent
import kotlinx.browser.document
import kotlinx.browser.window
import kotlin.math.*
fun getImage(path: String): HTMLImageElement {
val image = window.document.createElement("img") as HTMLImageElement
image.src = path
return image
}
val canvas = initializeCanvas()
fun initializeCanvas(): HTMLCanvasElement {
val canvas = document.createElement("canvas") as HTMLCanvasElement
val context = canvas.getContext("2d") as CanvasRenderingContext2D
context.canvas.width = window.innerWidth.toInt()
context.canvas.height = window.innerHeight.toInt()
document.body!!.appendChild(canvas)
return canvas
}
val context: CanvasRenderingContext2D
get() {
return canvas.getContext("2d") as CanvasRenderingContext2D
}
abstract class Shape() {
abstract fun draw(state: CanvasState)
// these two abstract methods defines that our shapes can be dragged
operator abstract fun contains(mousePos: Vector): Boolean
abstract var pos: Vector
var selected: Boolean = false
// a couple of helper extension methods we'll be using in the derived classes
fun CanvasRenderingContext2D.shadowed(shadowOffset: Vector, alpha: Double, render: CanvasRenderingContext2D.() -> Unit) {
save()
shadowColor = "rgba(100, 100, 100, $alpha)"
shadowBlur = 5.0
shadowOffsetX = shadowOffset.x
shadowOffsetY = shadowOffset.y
render()
restore()
}
fun CanvasRenderingContext2D.fillPath(constructPath: CanvasRenderingContext2D.() -> Unit) {
beginPath()
constructPath()
closePath()
fill()
}
}
val logoImage by lazy { getImage("https://play.kotlinlang.org/assets/kotlin-logo.svg") }
val logoImageSize = v(64.0, 64.0)
val Kotlin = Logo(v(canvas.width / 2.0 - logoImageSize.x / 2.0 - 64, canvas.height / 2.0 - logoImageSize.y / 2.0 - 64))
class Logo(override var pos: Vector) : Shape() {
val relSize: Double = 0.18
val shadowOffset = v(-3.0, 3.0)
var size: Vector = logoImageSize * relSize
// get-only properties like this saves you lots of typing and are very expressive
val position: Vector
get() = if (selected) pos - shadowOffset else pos
fun drawLogo(state: CanvasState) {
if (!logoImage.complete) {
state.changed = true
return
}
size = logoImageSize * (state.size.x / logoImageSize.x) * relSize
state.context.drawImage(getImage("https://play.kotlinlang.org/assets/kotlin-logo.svg"), 0.0, 0.0,
logoImageSize.x, logoImageSize.y,
position.x, position.y,
size.x, size.y)
}
override fun draw(state: CanvasState) {
val context = state.context
if (selected) {
// using helper we defined in Shape class
context.shadowed(shadowOffset, 0.2) {
drawLogo(state)
}
} else {
drawLogo(state)
}
}
override fun contains(mousePos: Vector): Boolean = mousePos.isInRect(pos, size)
val centre: Vector
get() = pos + size * 0.5
}
val gradientGenerator by lazy { RadialGradientGenerator(context) }
class Creature(override var pos: Vector, val state: CanvasState) : Shape() {
val shadowOffset = v(-5.0, 5.0)
val colorStops = gradientGenerator.getNext()
val relSize = 0.05
// these properties have no backing fields and in java/javascript they could be represented as little helper functions
val radius: Double
get() = state.width * relSize
val position: Vector
get() = if (selected) pos - shadowOffset else pos
val directionToLogo: Vector
get() = (Kotlin.centre - position).normalized
//notice how the infix call can make some expressions extremely expressive
override fun contains(mousePos: Vector) = pos distanceTo mousePos < radius
// defining more nice extension functions
fun CanvasRenderingContext2D.circlePath(position: Vector, rad: Double) {
arc(position.x, position.y, rad, 0.0, 2 * PI, false)
}
//notice we can use an extension function we just defined inside another extension function
fun CanvasRenderingContext2D.fillCircle(position: Vector, rad: Double) {
fillPath {
circlePath(position, rad)
}
}
override fun draw(state: CanvasState) {
val context = state.context
if (!selected) {
drawCreature(context)
} else {
drawCreatureWithShadow(context)
}
}
fun drawCreature(context: CanvasRenderingContext2D) {
context.fillStyle = getGradient(context)
context.fillPath {
tailPath(context)
circlePath(position, radius)
}
drawEye(context)
}
fun getGradient(context: CanvasRenderingContext2D): CanvasGradient {
val gradientCentre = position + directionToLogo * (radius / 4)
val gradient = context.createRadialGradient(gradientCentre.x, gradientCentre.y, 1.0, gradientCentre.x, gradientCentre.y, 2 * radius)
for (colorStop in colorStops) {
gradient.addColorStop(colorStop.first, colorStop.second)
}
return gradient
}
fun tailPath(context: CanvasRenderingContext2D) {
val tailDirection = -directionToLogo
val tailPos = position + tailDirection * radius * 1.0
val tailSize = radius * 1.6
val angle = PI / 6.0
val p1 = tailPos + tailDirection.rotatedBy(angle) * tailSize
val p2 = tailPos + tailDirection.rotatedBy(-angle) * tailSize
val middlePoint = position + tailDirection * radius * 1.0
context.moveTo(tailPos.x, tailPos.y)
context.lineTo(p1.x, p1.y)
context.quadraticCurveTo(middlePoint.x, middlePoint.y, p2.x, p2.y)
context.lineTo(tailPos.x, tailPos.y)
}
fun drawEye(context: CanvasRenderingContext2D) {
val eyePos = directionToLogo * radius * 0.6 + position
val eyeRadius = radius / 3
val eyeLidRadius = eyeRadius / 2
context.fillStyle = "#FFFFFF"
context.fillCircle(eyePos, eyeRadius)
context.fillStyle = "#000000"
context.fillCircle(eyePos, eyeLidRadius)
}
fun drawCreatureWithShadow(context: CanvasRenderingContext2D) {
context.shadowed(shadowOffset, 0.7) {
context.fillStyle = getGradient(context)
fillPath {
tailPath(context)
context.circlePath(position, radius)
}
}
drawEye(context)
}
}
class CanvasState(val canvas: HTMLCanvasElement) {
var width = canvas.width
var height = canvas.height
val size: Vector
get() = v(width.toDouble(), height.toDouble())
val context = creatures.context
var changed = true
var shapes = mutableListOf<Shape>()
var selection: Shape? = null
var dragOff = Vector()
val interval = 1000 / 30
init {
canvas.onmousedown = { e: MouseEvent ->
changed = true
selection = null
val mousePos = mousePos(e)
for (shape in shapes) {
if (mousePos in shape) {
dragOff = mousePos - shape.pos
shape.selected = true
selection = shape
break
}
}
}
canvas.onmousemove = { e: MouseEvent ->
if (selection != null) {
selection!!.pos = mousePos(e) - dragOff
changed = true
}
}
canvas.onmouseup = { e: MouseEvent ->
if (selection != null) {
selection!!.selected = false
}
selection = null
changed = true
this
}
canvas.ondblclick = { e: MouseEvent ->
val newCreature = Creature(mousePos(e), this@CanvasState)
addShape(newCreature)
changed = true
this
}
window.setInterval({
draw()
}, interval)
}
fun mousePos(e: MouseEvent): Vector {
var offset = Vector()
var element: HTMLElement? = canvas
while (element != null) {
val el: HTMLElement = element
offset += Vector(el.offsetLeft.toDouble(), el.offsetTop.toDouble())
element = el.offsetParent as HTMLElement?
}
return Vector(e.pageX, e.pageY) - offset
}
fun addShape(shape: Shape) {
shapes.add(shape)
changed = true
}
fun clear() {
context.fillStyle = "#D0D0D0"
context.fillRect(0.0, 0.0, width.toDouble(), height.toDouble())
context.strokeStyle = "#000000"
context.lineWidth = 4.0
context.strokeRect(0.0, 0.0, width.toDouble(), height.toDouble())
}
fun draw() {
if (!changed) return
changed = false
clear()
for (shape in shapes.asReversed()) {
shape.draw(this)
}
Kotlin.draw(this)
}
}
class RadialGradientGenerator(val context: CanvasRenderingContext2D) {
val gradients = mutableListOf<Array<out Pair<Double, String>>>()
var current = 0
fun newColorStops(vararg colorStops: Pair<Double, String>) {
gradients.add(colorStops)
}
init {
newColorStops(Pair(0.0, "#F59898"), Pair(0.5, "#F57373"), Pair(1.0, "#DB6B6B"))
newColorStops(Pair(0.39, "rgb(140,167,209)"), Pair(0.7, "rgb(104,139,209)"), Pair(0.85, "rgb(67,122,217)"))
newColorStops(Pair(0.0, "rgb(255,222,255)"), Pair(0.5, "rgb(255,185,222)"), Pair(1.0, "rgb(230,154,185)"))
newColorStops(Pair(0.0, "rgb(255,209,114)"), Pair(0.5, "rgb(255,174,81)"), Pair(1.0, "rgb(241,145,54)"))
newColorStops(Pair(0.0, "rgb(132,240,135)"), Pair(0.5, "rgb(91,240,96)"), Pair(1.0, "rgb(27,245,41)"))
newColorStops(Pair(0.0, "rgb(250,147,250)"), Pair(0.5, "rgb(255,80,255)"), Pair(1.0, "rgb(250,0,217)"))
}
fun getNext(): Array<out Pair<Double, String>> {
val result = gradients.get(current)
current = (current + 1) % gradients.size
return result
}
}
fun v(x: Double, y: Double) = Vector(x, y)
class Vector(val x: Double = 0.0, val y: Double = 0.0) {
operator fun plus(v: Vector) = v(x + v.x, y + v.y)
operator fun unaryMinus() = v(-x, -y)
operator fun minus(v: Vector) = v(x - v.x, y - v.y)
operator fun times(koef: Double) = v(x * koef, y * koef)
infix fun distanceTo(v: Vector) = sqrt((this - v).sqr)
fun rotatedBy(theta: Double): Vector {
val sin = sin(theta)
val cos = cos(theta)
return v(x * cos - y * sin, x * sin + y * cos)
}
fun isInRect(topLeft: Vector, size: Vector) = (x >= topLeft.x) && (x <= topLeft.x + size.x) &&
(y >= topLeft.y) && (y <= topLeft.y + size.y)
val sqr: Double
get() = x * x + y * y
val normalized: Vector
get() = this * (1.0 / sqrt(sqr))
}
fun main(args: Array<String>) {
CanvasState(canvas).apply {
addShape(Kotlin)
addShape(Creature(size * 0.25, this))
addShape(Creature(size * 0.75, this))
}
}
Html Builder
Kotlin provides you with an option to describe structured data in a declarative style with builders.
Below is an example of a type-safe Groovy-style builder. In this example, we will describe an HTML page in Kotlin.
package html
fun main() {
val result = html { // 1
head { // 2
title { +"HTML encoding with Kotlin" }
}
body { // 2
h1 { +"HTML encoding with Kotlin" }
p {
+"this format can be used as an" // 3
+"alternative markup to HTML" // 3
}
// an element with attributes and text content
a(href = "http://kotlinlang.org") { +"Kotlin" }
// mixed content
p {
+"This is some"
b { +"mixed" }
+"text. For more see the"
a(href = "http://kotlinlang.org") {
+"Kotlin"
}
+"project"
}
p {
+"some text"
ul {
for (i in 1..5)
li { +"${i}*2 = ${i*2}" }
}
}
}
}
println(result)
}
interface Element {
fun render(builder: StringBuilder, indent: String)
}
class TextElement(val text: String) : Element {
override fun render(builder: StringBuilder, indent: String) {
builder.append("$indent$text\n")
}
}
@DslMarker
annotation class HtmlTagMarker
@HtmlTagMarker
abstract class Tag(val name: String) : Element {
val children = arrayListOf<Element>()
val attributes = hashMapOf<String, String>()
protected fun <T : Element> initTag(tag: T, init: T.() -> Unit): T {
tag.init()
children.add(tag)
return tag
}
override fun render(builder: StringBuilder, indent: String) {
builder.append("$indent<$name${renderAttributes()}>\n")
for (c in children) {
c.render(builder, indent + " ")
}
builder.append("$indent</$name>\n")
}
private fun renderAttributes(): String {
val builder = StringBuilder()
for ((attr, value) in attributes) {
builder.append(" $attr=\"$value\"")
}
return builder.toString()
}
override fun toString(): String {
val builder = StringBuilder()
render(builder, "")
return builder.toString()
}
}
abstract class TagWithText(name: String) : Tag(name) {
operator fun String.unaryPlus() {
children.add(TextElement(this))
}
}
class HTML() : TagWithText("html") {
fun head(init: Head.() -> Unit) = initTag(Head(), init)
fun body(init: Body.() -> Unit) = initTag(Body(), init)
}
class Head() : TagWithText("head") {
fun title(init: Title.() -> Unit) = initTag(Title(), init)
}
class Title() : TagWithText("title")
abstract class BodyTag(name: String) : TagWithText(name) {
fun b(init: B.() -> Unit) = initTag(B(), init)
fun p(init: P.() -> Unit) = initTag(P(), init)
fun h1(init: H1.() -> Unit) = initTag(H1(), init)
fun ul(init: UL.() -> Unit) = initTag(UL(), init)
fun a(href: String, init: A.() -> Unit) {
val a = initTag(A(), init)
a.href = href
}
}
class Body() : BodyTag("body")
class UL() : BodyTag("ul") {
fun li(init: LI.() -> Unit) = initTag(LI(), init)
}
class B() : BodyTag("b")
class LI() : BodyTag("li")
class P() : BodyTag("p")
class H1() : BodyTag("h1")
class A : BodyTag("a") {
var href: String
get() = attributes["href"]!!
set(value) {
attributes["href"] = value
}
}
fun html(init: HTML.() -> Unit): HTML {
val html = HTML()
html.init()
return html
}
-
html
is actually a function call that takes a lambda expression as an argument.html
function takes one parameter which is itself a function. The type of the function isHTML.() -> Unit
, which is a function type with receiver. This means that we need to pass an instance of typeHTML
(a receiver) to the function, and we can call members of that instance inside the function. -
head
andbody
are member functions of theHTML
class. -
Adds the text to tags by calling the
unaryPlus()
operation, like+"HTML encoding with Kotlin"
.
For details see: Type Safe Builders