A Live Developer Journal

Kotlin Koans Tried And Abandoned

Learning the kotlin language by going through Kotlin Koans.

Default and Named Arguments


fun joinToString(
  separator: String = ", ",
  prefix: String = "",
  postfix: Sting = "",
): String


something.joinToString(prefix = "[", postfix = "]")

Default arguments


fun(foo(name: String, number: Int = 42, toUpperCase: Boolean = false) =
  (if (toUpperCase) name.toUpperCase() else name) + number

fun useFoo() = listOf(
  foo("a"),
  foo("b", number = 1),
  foo("c", toUpperCase = true),
  foo(name = "d", number = 2, toUpperCase = true)

Lambdas

A higher-order function is a function that takes functions as parameters, or returns a function.

Lambda expressions and anonymous functions are 'function literals': Functions that are not declared, but passes immediately as an expression.

fun containsEven(collection: Collection): Boolean = collection.any { it % 2 == 0 }

The it keyword refers to the parameter when a lambda expression only has one parameter (which is common).

Strings


val month = "(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)"

fun getPattern(): String: = """\d{2} ${month} \d{4}"""

Data Classes


data class Person(val name: String, val age: Int)

fun getPeople(): List {
    return listOf(Person("Alice", 29), Person("Bob", 31))
}

Gah, this way of learning is not for me. Going to leave this tutorial now, ick.