Functional programming examples
Java’s Function, Consumer, and Predicate correspond to Kotlin function types, and so does any functional interface the domain defines, such as a Processor that turns one domain object into another. Kotlin writes the input and result types around →; Unit means the function does not return a useful value.
| Java type | Kotlin type | Example |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
For example, the declarations below create equivalent functions in each language.
1import java.util.function.Consumer;
2import java.util.function.Function;
3import java.util.function.Predicate;
4
5class FunctionalTypes {
6 @FunctionalInterface
7 interface Processor<T, R> {
8 R process(T input);
9 }
10
11 static class User {
12 boolean active;
13 }
14
15 static class Order {
16 double total;
17 }
18
19 static class Receipt {
20 double amount;
21
22 Receipt(double amount) {
23 this.amount = amount;
24 }
25 }
26
27 static Function<String, Integer> length = text -> text.length();
28 static Consumer<String> print = text -> System.out.println(text);
29 static Processor<Order, Receipt> checkout = order -> new Receipt(order.total);
30 static Predicate<User> isActive = user -> user.active;
31}1data class User(val active: Boolean)
2data class Order(val total: Double)
3data class Receipt(val amount: Double)
4
5val length: (String) -> Int = { text -> text.length }
6val print: (String) -> Unit = { text -> println(text) }
7val checkout: (Order) -> Receipt = { order -> Receipt(order.total) }
8val isActive: (User) -> Boolean = { user -> user.active }Use map to transform every number in a list into its square.
1fun main() {
2 val numbers = listOf(1, 2, 3, 4, 5)
3 val squares = numbers.map { it * it }
4 println(squares)
5}Group people by first name and count how many people are in each group.
1data class Person(val firstName: String, val lastName: String)
2
3fun main() {
4 val people = listOf(
5 Person("Alice", "Smith"),
6 Person("Bob", "Jones"),
7 Person("Alice", "Johnson")
8 )
9
10 val nameCount = people.groupingBy { it.firstName }.eachCount()
11 println(nameCount)
12}Use fold to accumulate an order total from each product’s price and quantity.
1import java.math.BigDecimal
2
3data class Product(val name: String, val price: BigDecimal)
4data class OrderLine(val product: Product, val quantity: Int)
5
6fun main() {
7 val orders = listOf(
8 OrderLine(Product("Laptop", BigDecimal("1200.00")), 2),
9 OrderLine(Product("Mouse", BigDecimal("25.50")), 3)
10 )
11
12 val totalPrice = orders.fold(BigDecimal.ZERO) { acc, line ->
13 acc + (line.product.price * line.quantity.toBigDecimal())
14 }
15
16 println(totalPrice)
17}Define an extension function that converts a string to camel case.
1fun String.toCamelCase(): String =
2 this.split(" ")
3 .filter { it.isNotBlank() }
4 .mapIndexed { index, word ->
5 if (index == 0) word.lowercase()
6 else word.lowercase().replaceFirstChar { it.uppercase() }
7 }
8 .joinToString("")
9
10fun main() {
11 val input = "Hello world"
12 println(input.toCamelCase())
13}Use all to check whether every square in a battleship is a hit.
1enum class Square { EMPTY, HIT, MISS }
2
3fun main() {
4 val battleship = listOf(Square.HIT, Square.HIT, Square.HIT)
5 val isSunken = battleship.all { it == Square.HIT }
6 println(isSunken)
7}Chain collection operations to split sentences into distinct, lowercase words.
1fun main() {
2 val sentences = listOf(
3 "Java runs on the JVM",
4 "Kotlin also runs on the JVM"
5 )
6
7 val distinctWords: List<String> = sentences
8 .flatMap { it.split(Regex("\\s+")) }
9 .filter { it.isNotBlank() }
10 .map { it.lowercase() }
11 .distinct()
12 println(distinctWords)
13}