Functional programming examples
1fun main() {
2 val numbers = listOf(1, 2, 3, 4, 5)
3 val squares = numbers.map { it * it }
4 println(squares)
5} 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} 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} 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}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} 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}