This document provides an overview of the Kotlin programming language. It defines Kotlin as a statically typed language that targets the JVM and JavaScript, is 100% interoperable with Java, and was created by JetBrains as a better alternative to Java. The document then covers 10 features of Kotlin, including null safety, data classes, extension functions, smart casts, and support for functional programming patterns. It provides code examples to demonstrate how these features work in Kotlin.
6. What is Kotlin
● Statically typed programming language targeting JVM, JavaScript
● Started in 2010 by the JetBrains
● They needed a language:
○ Expressive, Toolable, Interoperable, Pragmatic
● 100% interoperable with Java
● KClasses are compiled to Java bytecode (Java 6+)
8. What is Kotlin
“Kotlin is not business model for JetBrains, it is a tool to create business
tools in more efficient language”
9. What is Kotlin
“Kotlin is designed to be an industrial-strength object-oriented language,
and to be a better language than Java but still be fully interoperable with
Java code, allowing companies to make a gradual migration from Java to
Kotlin.” – Andrey Breslav, Development Lead for Kotlin
15. What is Kotlin / Demo
public void updateWeather(int degrees) {
String description;
Color color;
if (degrees < 5) {
description = "cold";
color = Color.BLUE;
} else if (degrees < 23) {
description = "mild";
color = Color.ORANGE;
} else {
description = "hot";
color = Color.RED;
}
}
You can do better with Kotlin by Svetlana Isakova
16. What is Kotlin / Demo
public void updateWeather(int degrees) {
String description;
Color color;
if (degrees < 5) {
description = "cold";
color = Color.BLUE;
} else if (degrees < 23) {
description = "mild";
color = Color.ORANGE;
} else {
description = "hot";
color = Color.RED;
}
}
fun updateWeather(degrees: Int) {
val description: String
val color: Color
if (degrees < 5) {
description = "cold"
color = Color.BLUE
} else if (degrees < 23) {
description = "mild"
color = Color.ORANGE
} else {
description = "hot"
color = Color.RED
}
}
17. What is Kotlin / Demo
public void updateWeather(int degrees) {
String description;
Color color;
if (degrees < 5) {
description = "cold";
color = Color.BLUE;
} else if (degrees < 23) {
description = "mild";
color = Color.ORANGE;
} else {
description = "hot";
color = Color.RED;
}
}
fun updateWeather(degrees: Int) {
val description: String
val color: Color
if (degrees < 5) {
description = "cold"
color = Color.BLUE
} else if (degrees < 23) {
description = "mild"
color = Color.ORANGE
} else {
description = "hot"
color = Color.RED
}
}
18. What is Kotlin / Demo
fun updateWeather(degrees: Int) {
val description: String
val color: Color
if (degrees < 5) {
description = "cold"
color = Color.BLUE
} else if (degrees < 23) {
description = "mild"
color = Color.ORANGE
} else {
description = "hot"
color = Color.RED
}
}
fun updateWeather(degrees: Int) {
val (description: String, color: Color) = if (degrees < 5) {
Pair("cold", Color.BLUE)
} else if (degrees < 23) {
Pair("mild", Color.ORANGE)
} else {
Pair("hot", Color.RED)
}
}
19. What is Kotlin / Demo
fun updateWeather(degrees: Int) {
val (description: String, color: Color) = if (degrees < 5) {
Pair("cold", Color.BLUE)
} else if (degrees < 23) {
Pair("mild", Color.ORANGE)
} else {
Pair("hot", Color.RED)
}
}
20. What is Kotlin / Demo
fun updateWeather(degrees: Int) {
val (description, color) = if (degrees < 5) {
Pair("cold", Color.BLUE)
} else if (degrees < 23) {
Pair("mild", Color.ORANGE)
} else {
Pair("hot", Color.RED)
}
}
21. What is Kotlin / Demo
fun updateWeather(degrees: Int) {
val (description, color) = if (degrees < 5) {
Pair("cold", Color.BLUE)
} else if (degrees < 23) {
Pair("mild", Color.ORANGE)
} else {
Pair("hot", Color.RED)
}
}
22. What is Kotlin / Demo
fun updateWeather(degrees: Int) {
val (description, color) = when {
degrees < 5 -> Pair("cold", Color.BLUE)
degrees < 23 -> Pair("mild", Color.ORANGE)
else -> Pair("hot", Color.RED)
}
}
23. What is Kotlin / Demo
fun updateWeather(degrees: Int) {
val (description, color) = when {
degrees < 5 -> Pair("cold", Color.BLUE)
degrees < 23 -> Pair("mild", Color.ORANGE)
else -> Pair("hot", Color.RED)
}
}
24. What is Kotlin / Demo
fun updateWeather(degrees: Int) {
val (description, color) = when {
degrees < 5 -> "cold" to Color.BLUE
degrees < 23 -> "mild" to Color.ORANGE
else -> "hot" to Color.RED
}
}
25. What is Kotlin / Demo
fun updateWeather(degrees: Int) {
val (description, color) = when {
degrees < 5 -> "cold" to Color.BLUE
degrees < 23 -> "mild" to Color.ORANGE
else -> "hot" to Color.RED
}
}
public void updateWeather(int degrees) {
String description;
Color color;
if (degrees < 5) {
description = "cold";
color = Color.BLUE;
} else if (degrees < 23) {
description = "mild";
color = Color.ORANGE;
} else {
description = "hot";
color = Color.RED;
}
}
27. 1. Null Safety / 10 Features
var a: String = "abc"
a = null // compilation error
var b: String? = "abc"
b = null // ok
val x: String? = "Hi"
x.length // Does not compile.
val y: String = null // Does not compile.
28. 1. Null Safety / 10 Features
var a: String = "abc"
a = null // compilation error
var b: String? = "abc"
b = null // ok
val x: String? = "Hi"
x.length // Does not compile.
val y: String = null // Does not compile.
29. 1. Null Safety / 10 Features
var a: String = "abc"
a = null // compilation error
var b: String? = "abc"
b = null // ok
val x: String? = "Hi"
x.length // Does not compile.
val y: String = null // Does not compile.
30. 1. Null Safety / 10 Features
var a: String = "abc"
a = null // compilation error
var b: String? = "abc"
b = null // ok
val x: String? = "Hi"
x.length // Does not compile.
val y: String = null // Does not compile.
31. 1. Null Safety / 10 Features
var a: String = "abc"
a = null // compilation error
var b: String? = "abc"
b = null // ok
val x: String? = "Hi"
x.length // Does not compile.
val y: String = null // Does not compile.
32. 1. Null Safety / 10 Features
var a: String = "abc"
a = null // compilation error
var b: String? = "abc"
b = null // ok
val x: String? = "Hi"
x.length // Does not compile.
val y: String = null // Does not compile.
33. 1. Null Safety / 10 Features
var a: String = "abc"
a = null // compilation error
var b: String? = "abc"
b = null // ok
val x: String? = "Hi"
x.length // Does not compile.
val y: String = null // Does not compile.
34. 1. Null Safety / 10 Features
if (x != null) {
x.length // Compiles! Not idiomatic just to get length!
}
// Same as above (IntelliJ auto-suggested the change).
x?.length
// Elvis operator.
val len = x?.length ?: -1
val len = x!!.length // Will throw if null. Rarely used
35. 1. Null Safety / 10 Features
if (x != null) {
x.length // Compiles! Not idiomatic just to get length!
}
// Same as above (IntelliJ auto-suggested the change).
x?.length
// Elvis operator.
val len = x?.length ?: -1
val len = x!!.length // Will throw if null. Rarely used
36. 1. Null Safety / 10 Features
if (x != null) {
x.length // Compiles! Not idiomatic just to get length!
}
// Same as above (IntelliJ auto-suggested the change).
x?.length
// Elvis operator.
val len = x?.length ?: -1
val len = x!!.length // Will throw if null. Rarely used
37. 1. Null Safety / 10 Features
if (x != null) {
x.length // Compiles! Not idiomatic just to get length!
}
// Same as above (IntelliJ auto-suggested the change).
x?.length
// Elvis operator.
val len = x?.length ?: -1
val len = x!!.length // Will throw if null. Rarely used
39. 2. Data Class / 10 Features
● For simple classes which mainly hold data, we can avoid a lot of boilerplate
compared to Java code
40. 2. Data Class / 10 Features
● For simple classes which mainly hold data, we can avoid a lot of boilerplate
compared to Java code
● Consider the following task:
○ Create Country object which holds data about id and name
43. 3. Data Class / 10 Features
● Kotlin generate hashCode(), equals(), toString()
44. 3. Data Class / 10 Features
● But that’s not all what we could with data classes!
○ We can easily make copies of data classes
45. 3. Data Class / 10 Features
● But that’s not all what we could with data classes!
○ We can easily make copies of data classes
val customer = Customer(id = 2001,
name = "Vaclav Souhrada",
email = "vsouhrada@email.to")
46. 3. Data Class / 10 Features
● But that’s not all what we could with data classes!
○ We can easily make copies of data classes
val customer = Customer(id = 2001,
name = "Vaclav Souhrada",
email = "vsouhrada@email.to")
val updatedCst = customer.copy(email = "vaclav_souhrada@email.com")
49. 3. Extension Functions / 10 Features
● Kotlin allows us to extend the functionality of existing classes without inheriting from them.
fun String.capitalize(): String {
return this.toUpperCase()
}
50. 3. Extension Functions / 10 Features
● Kotlin allows us to extend the functionality of existing classes without inheriting from them.
fun String.hello() {
println("Hello, $this!")
}
51. 3. Extension Functions / 10 Features
● Kotlin allows us to extend the functionality of existing classes without inheriting from them.
fun String.hello() {
println("Hello, $this!")
}
fun String.and(input: String): String {
return "${this} $input"
}
52. 3. Extension Functions / 10 Features
● Kotlin allows us to extend the functionality of existing classes without inheriting from them.
fun main(args: Array<String>) {
// prints VACLAV SOUHRADA
println("vaclav souhrada".capitalize())
"Vaclav".hello() // prints 'Hello, Vaclav!'
var testString = "This is a string".and("This is another")
println(testString) // prints 'This is a string This is another'
}
fun String.hello() {
println("Hello, $this!")
}
fun String.and(input: String): String
{
return "${this} $input"
}
53. 3. Extension Functions / 10 Features
● Kotlin allows us to extend the functionality of existing classes without inheriting from them.
val gson = Gson()
54. 3. Extension Functions / 10 Features
● Kotlin allows us to extend the functionality of existing classes without inheriting from them.
val gson = Gson()
fun Any.toJSON(): String {
return gson.toJson(this)
}
55. 3. Extension Functions / 10 Features
● Kotlin allows us to extend the functionality of existing classes without inheriting from them.
val gson = Gson()
fun Any.toJSON(): String {
return gson.toJson(this)
}
val customer = Customer(id = 2001, name = "Vaclav Souhrada", email =
"vsouhrada@email.com")
56. 3. Extension Functions / 10 Features
● Kotlin allows us to extend the functionality of existing classes without inheriting from them.
val gson = Gson()
fun Any.toJSON(): String {
return gson.toJson(this)
}
val customer = Customer(id = 2001, name = "Vaclav Souhrada", email =
"vsouhrada@email.com")
val json = customer.toJSON()
58. 4. Smart Cast / 10 Features
if (obj instanceof String) {
}
59. 4. Smart Cast / 10 Features
if (obj instanceof String) {
System.out.println(((String) obj).length());
}
60. 4. Smart Cast / 10 Features
if (obj instanceof String) {
System.out.println(((String) obj).length());
}
if (obj is String) {
}
61. 4. Smart Cast / 10 Features
if (obj instanceof String) {
System.out.println(((String) obj).length());
}
if (obj is String) {
print(obj.length)
}
62. 4. Smart Cast / 10 Features
if (obj instanceof String) {
System.out.println(((String) obj).length());
}
if (!(obj instanceof String)) {
System.out.println("Not a String");
}
if (obj is String) {
print(obj.length)
}
63. 4. Smart Cast / 10 Features
if (obj instanceof String) {
System.out.println(((String) obj).length());
}
if (!(obj instanceof String)) {
System.out.println("Not a String");
}
if (obj is String) {
print(obj.length)
}
if (obj !is String) { // !(obj is String)
print("Not a String")
}
64. 4. Smart Cast / 10 Features
if (obj instanceof String) {
System.out.println(((String) obj).length());
}
if (!(obj instanceof String)) {
System.out.println("Not a String");
} else {
System.out.println(((String) obj).length());
}
if (obj is String) {
print(obj.length)
}
if (obj !is String) { // !(obj is String)
print("Not a String")
}
65. 4. Smart Cast / 10 Features
if (obj instanceof String) {
System.out.println(((String) obj).length());
}
if (!(obj instanceof String)) {
System.out.println("Not a String");
} else {
System.out.println(((String) obj).length());
}
if (obj is String) {
print(obj.length)
}
if (obj !is String) { // !(obj is String)
print("Not a String")
} else {
print(obj.length)
}
66. 4. Smart Cast / 10 Features
if (obj instanceof String) {
System.out.println(((String) obj).length());
}
if (!(obj instanceof String)) {
System.out.println("Not a String");
} else {
System.out.println(((String) obj).length());
}
if (obj is String) {
print(obj.length)
}
if (obj !is String) { // !(obj is String)
print("Not a String")
} else {
print(obj.length)
}
74. 6. Functional Programming / 10 Features
● Combination of lambda expression and the Kotlin lib. makes our day easier
when we working with collections
val numbers = arrayListOf(10 ,5 , -9, 9, 11, 5, -6)
75. 6. Functional Programming / 10 Features
● Combination of lambda expression and the Kotlin lib. makes our day easier
when we working with collections
val numbers = arrayListOf(10 ,5 , -9, 9, 11, 5, -6)
val nonNegative = numbers.filter { it >= 0}
println(nonNegative) // [10, 5, 9, 11, 5]
76. 6. Functional Programming / 10 Features
● Combination of lambda expression and the Kotlin lib. makes our day easier
when we working with collections
val numbers = arrayListOf(10 ,5 , -9, 9, 11, 5, -6)
val nonNegative = numbers.filter { it >= 0}
println(nonNegative) // [10, 5, 9, 11, 5]
77. 6. Functional Programming / 10 Features
● Combination of lambda expression and the Kotlin lib. makes our day easier
when we working with collections
val numbers = arrayListOf(10 ,5 , -9, 9, 11, 5, -6)
// Sum of all elements: 25
println(numbers.foldRight(0, { a, b -> a + b }))
78. 6. Functional Programming / 10 Features
● Combination of lambda expression and the Kotlin lib. makes our day easier
when we working with collections
val numbers = arrayListOf(10 ,5 , -9, 9, 11, 5, -6)
// Sum of all elements: 25
println(numbers.foldRight(0, { a, b -> a + b }))
//20 10 -18 18 22 10 -12
numbers.forEach { println("${it * 2} ") }
79. 6. Functional Programming / 10 Features
● Combination of lambda expression and the Kotlin lib. makes our day easier
when we working with collections
val numbers = arrayListOf(10 ,5 , -9, 9, 11, 5, -6)
// Sum of all elements: 25
println(numbers.foldRight(0, { a, b -> a + b }))
//20 10 -18 18 22 10 -12
numbers.forEach { println("${it * 2} ") }
val kindOfNumbers: Iterable<String> = numbers.filter { it < 0 }
.map { "$it is negative" }
80. 6. Functional Programming / 10 Features
● Combination of lambda expression and the Kotlin lib. makes our day easier
when we working with collections
val numbers = arrayListOf(10 ,5 , -9, 9, 11, 5, -6)
// Sum of all elements: 25
println(numbers.foldRight(0, { a, b -> a + b }))
//20 10 -18 18 22 10 -12
numbers.forEach { println("${it * 2} ") }
val kindOfNumbers: Iterable<String> = numbers.filter { it < 0 }
.map { "$it is negative" }
println(kindOfNumbers) // [-9 is negative, -6 is negative]
82. 7. Type Inference / 10 Features
● In Kotlin, you do not have to specify the type of each variable explicitly:
val name = "Vaclav" // val name: String = "Vaclav"
83. 7. Type Inference / 10 Features
● In Kotlin, you do not have to specify the type of each variable explicitly:
val name = "Vaclav"
val age = 31
84. 7. Type Inference / 10 Features
● In Kotlin, you do not have to specify the type of each variable explicitly:
val name = "Vaclav"
val age = 31
// Only need Iterable interface
val list: Iterable<Double> = arrayListOf(1.0, 0.0, 3.1415, 2.718)
85. 7. Type Inference / 10 Features
● In Kotlin, you do not have to specify the type of each variable explicitly:
val name = "Vaclav"
val age = 31
// Only need Iterable interface
val list: Iterable<Double> = arrayListOf(1.0, 0.0, 3.1415, 2.718)
// Type is ArrayList
val arrayList = arrayListOf("Kotlin", "Scala", "Groovy")
87. 8. Default Arguments / 10 Features
In Java, we often have to duplicate code in order define different variants of a method or
constructor:
88. 8. Default Arguments / 10 Features
All this stuff we can remove when we switch to Kotlin by using default arguments.
class OperatorInfoInKotlin(
val uuid: String = UUID.randomUUID().toString(),
val name: String,
val hasAccess: Boolean = true,
val isAdmin: Boolean = false,
val notes: String = "") {}
90. 9. Named Arguments / 10 Features
Default arguments become more powerful in a combination with named arguments:
OperatorInfoInKotlin(name = "Vaclav")
OperatorInfoInKotlin(name = "Vaclav", hasAccess = false, isAdmin = false, notes = "blabla")
new OperatorInfoInJava("Vaclav", false, false, "blabla");
92. 10. Collections / 10 Features
● In Kotlin we have:
○ higher-order functions
○ lambda expressions
○ operator overloading
○ lazy evaluation
○ lots of others useful methods to work with the collection.
93. 10. Collections / 10 Features
“What is an average age of employees in the company in Pilsen city?”
1.6 !!!public double getAverageAge(@NotNull List<Employee> employees) {
}
int ageSum = 0;
int count= 0;
for (Employee employee : employees) {
}
if ("Pilsen".equals(employee.getCity()) {
}
ageSum += employee.getAge();
count++;
if (count == 0) return 0
return ageSum / count;
94. 10. Collections / 10 Features
“What is an average age of employees in the company in Pilsen city?”
fun getAverageAge(val employees: List<Employee>): Double {
}
.map{ it.age }employees.filter{ it.city == City.PILSEN } .average()return
95. 10. Collections / 10 Features
“What is an average age of employees in the company in Pilsen city?”
public double getAverageAge(@NotNull List<Employee> employees) {
int ageSum = 0;
int count= 0;
for (Employee employee : employees) {
if ("Pilsen".equals(employee.getCity()) {
ageSum += employee.getAge();
count++;
}
}
if (count == 0) return 0
return ageSum / count;
}
fun getAverageAge(val employees: List<Employee>): Double {
return employees.filter{ it.city == City.PILSEN }.map{ it.age }.average()
}
96. 10. Collections / 10 Features
For more info you can see a very nice blog post from Antonio Leiva
https://antonioleiva.com/collection-operations-kotlin/
105. Gradle goes Kotlin
● Gradle is an advanced build management system based on Groovy
● Gradle is build tool with a focus on build automation for multi-language
development
● Official build tool for Android!
106. Gradle goes Kotlin
● Kotlin Meets Gradle (May 18, 2016)
○ Gradle and JetBrains announced a partnership to make Kotlin a first
class language for Gradle builds!
■ auto-completion and content assist
■ quick documentation
■ navigation to source
■ refactoring and more