This document provides an overview of the Kotlin programming language. Kotlin is a statically typed language that runs on the JVM and has design goals of being concise, safe, interoperable, and tool-friendly. It aims to mitigate weaknesses from Java like boilerplate code and unsafe nulls. Key features discussed include null safety, data classes, higher-order functions, lambdas, and functional-style programming with collections. The document also provides code samples and compares Kotlin's source code organization and packages to Java.
2. Kotlin
● Statically typed, runs on JVM.
● Design goals
○ Concise - less code
○ Safe - avoid null pointer, class cast
○ Interoperable
○ Tool-friendly - any Java IDE, command line - or https://try.kotlinlang.org
● Mitigate weaknesses from Java
○ e.g. boilerplate and unsafe arrays
● Enforce best practices
○ Immutability, designing for inheritance, ...
● Open sourced by JetBrains since February 2012
3. A taste of code: Hello world
package se.svt.java;
public class Main {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
package se.svt.kotlin
fun main(args: Array<String>) {
println("Hello, world!")
}
● Top-level function
● fun keyword
● ‘;’
4. Variables and data types
● Focus on immutability
○ val vs var
● Type inference
○ val name = "deadline horse"
● Same basic data types as Java
○ Byte, Short, Int, Long, Float, Double
○ Char, String
○ Boolean
● Variables cannot* be null - must be explicitly nullable
○ Prevents NullPointerException
○ var username: String = "deadline horse"
○ var username: String? = null
5. Classes and Interfaces
● Interface
○ interface Clickable {..}
○ java uses extends, implements, Kotlin just ‘:’
● Data classes
○ used as data container
○ data class Being(val name: String, val age: Int)
● Inheritance
○ final (default), open, and abstract
● Properties
○ lateinit var being: Being
○ lazy - Computed only on demand
■ val maybeNotNeeded by lazy {...}
6. A taste of code
package se.svt.java;
public class Being {
private String name;
private Integer age;
private Boolean human;
public Being(String name, Integer age,
Boolean human) {
this.name = name;
this.age = age;
this.human = human;
}
public Boolean canVote(){
return human && (age > 18);
}
public String getName() {
return name;
}
public Integer getAge() {
return age;
}
...
package se.svt.kotlin
class Being(val name: String, val age: Int, val human: Boolean){
fun canVote() = human && (age > 18)
}
7. Kotlin Standard Library
● A set of commonly used functions and annotations
○ https://kotlinlang.org/api/latest/jvm/stdlib/index.html
○ small size (Android)
● Higher order functions for functional programming
● Streams and Collections interface on top of java
○ List, Arrays, Maps, Sets, HashMap, HashSet etc.
○ Focus on immutability (read-only)
■ Lists: listOf() vs mutableListOf()
8. Control flow - conditionals
● Kotlin has if and when
○ when is like Java's switch but on steroids
● Both are expressions
● if replaces ternary condition operator
○ val msg = if (hasAccess) hello() else login()
if (isActive) {
doStuff()
} else {
cleanup()
}
when (state) {
WAITING -> wait()
RUNNING -> run()
}
9. Control flow - loops
● The for-loop
○ For any Iterable
○ Not (init; condition; action) structure!
● The while and do-while loop
○ Same as in Java and others
for (x in -3..3) {
doStuff()
}
for ((i, x) in array.withIndex()) {
println("the element at $i is $x")
}
10. Functions
fun ViewGroup.inflate(layout: Int): View {
return LayoutInflater.from(context).inflate(layout, this, false)
...
myViewGroup.inflate(R.layout.foo)
● Shorthand syntax
○ fun area(radius: Double) = Math.PI * radius * radius
● Default parameter values
○ fun join(strings:List<String>, delimiter: String = ",
", prefix = "", postfix = "")
● Named parameters
○ fun join(strings, prefix = "> ") : String {
"$prefix ${words.joinToString(separator = " ")}"
}
● Add extension function to any class:
11. Null handling - call operator
● Safe call operator
○ Propagates null if receiver is null
○ Cannot cause NPE
○ nullable?.someMethod()
● Elvis operator
○ Operation for null case
○ nullable?.someMethod() ?: someOtherMethod()
● Unsafe call operator
○ You assure compiler you know variable cannot be null!
○ Nullable!!.someMethod()
12. Kotlin features for functional programming
● Higher-order functions
○ As parameter
○ As return type
● Lambda expressions
○ Anonymous function, useful if only
used in one place
● Inline functions
○ Removing the overhead of lambdas
○ inline fun ...
fun runAsync(func: () -> Unit) {
Thread(Runnable { func() }).start()
}
fun doStuff() {
runAsync {
//access db, network etc
}
...
}
13. Kotlin features for functional programming con’t
Higher order functions for
collections
● take(n)
○ returns the first n items
● filter
○ returns items that match
predicate
● map
○ returns transform to other list
● sorted
○ returns a sorted list
● ...
val users = listOf(
Being("johnnyboy", 17, true),
Being("deadline horse", 35, false),
Being("rick", 61, true),
Being("morty", 14, true)
)
// chaining higher-order functions
val humans = users.filter { it.human }
.take(2)
.map { it.username }
.sorted()
14. Kotlin features for functional programming con’t
● Scope functions - higher order extensions from stdlib
● let: nullables or scoping
○ nullable?.let { doOnlyIfNotNull() }
● with: many calls on one (non-nullable!) object
● apply: initialization or builder-style
○ var p = Person().apply { name = "Deadline Horse";
age = 8 }
● also: actions on the side or validation
○ doSomething().also{require(...)log(...)}
● run: limit the scope of multiple local variables
receiver (this), argument (it) and result
16. Kotlin vs Java:Source code organization. Directories and
packages
Multiple classes in the same file
Any directory structure
One class per file
Packet <--> directory
18. Gotcha’s
Classes - sealed by default - explicit declare ‘open’
Autoconvertert from java. Need to check all those !!
Handling nulls from the JDK
The inner it - easy to get lost on nested lambdas