Zyn0.1.0

Functions

Functions are declared with fn. Parameters have their type written after a colon, and so does the result:

fn add(a: Int, b: Int): Int {
    return a + b
}

println(add(2, 3))
Output
5

#Expression bodies

A function that is one expression can be written with =. Its return type can then be left out:

fn square(x: Int) = x * x
fn isAdult(age: Int): Bool = age >= 18

println(square(9))
println(isAdult(15))
Output
81
false

A function without a return type, and with a block body, returns Unit (nothing useful).

#Default values and named arguments

Parameters can have default values. Arguments can be given by name, which also makes calls easier to read:

fn greet(name: String, greeting: String = "Hello", punctuation: String = "!"): String =
    "{greeting}, {name}{punctuation}"

println(greet("Ada"))
println(greet("Ada", "Welcome"))
println(greet("Ada", punctuation = "?"))
println(greet(greeting = "Hi", name = "Grace"))
Output
Hello, Ada!
Welcome, Ada!
Hello, Ada?
Hi, Grace!

Unnamed arguments come before named ones.

#Calling before declaring

Functions can be used before the line that declares them, so a file can be ordered however reads best:

println(isEven(10))

fn isEven(n: Int): Bool = n % 2 == 0
Output
true

#Recursion

fn factorial(n: Int): Int = if n <= 1 { 1 } else { n * factorial(n - 1) }

println(factorial(20))
Output
2432902008176640000

A recursive function needs its return type written out.

#Local functions

Functions can be declared inside other functions, and use the variables around them:

fn report(items: List<String>) {
    let prefix = "*"
    fn line(text: String) = println("{prefix} {text}")
    for item in items { line(item) }
}

report(["one", "two"])
Output
* one
* two

#Lambdas

A lambda is a function without a name, written in braces: parameters, ->, then the body. Its value is its last expression.

let add = { a: Int, b: Int -> a + b }
let shout = { text: String ->
    let loud = text.uppercase()
    loud + "!"
}
println(add(2, 3))
println(shout("hey"))
Output
5
HEY!

#Function types

A function's type is written (Parameter types) -> Result. Functions can take and return functions:

fn applyTwice(x: Int, f: (Int) -> Int): Int = f(f(x))

fn adder(amount: Int): (Int) -> Int = { x: Int -> x + amount }

let addTen = adder(10)
println(applyTwice(1, addTen))
println(applyTwice(3, { x: Int -> x * x }))
Output
21
81

#it and trailing lambdas

When the function a lambda is passed to says what its parameters are, their types can be left out, and a lambda with one parameter can use it instead of naming it. When a lambda is the last argument, it can go after the parentheses, and empty parentheses can be left out:

fn applyTwice(x: Int, f: (Int) -> Int): Int = f(f(x))

println(applyTwice(3) { it + 10 })
println([1, 2, 3].map { it * it })
println([1, 2, 3].map { n -> n * 2 })
println([4, 1, 3].sortedBy { -it })
Output
23
[1, 4, 9]
[2, 4, 6]
[4, 3, 1]

#Closures

A lambda can use, and change, the variables around it:

var count = 0
let increment = { count += 1 }
increment()
increment()
println(count)

fn counter(): () -> Int {
    var n = 0
    return {
        n += 1
        n
    }
}
let next = counter()
next()
next()
println(next())
Output
2
3
Note

In an if, while or for header, the { starts the body, so a trailing lambda there needs parentheses: if list.any({ it > 3 }) { ... }.

#Pipes

The pipe operator |> passes the value on its left as the first argument of the function on its right. Long chains of calls read from top to bottom, in the order they happen:

fn double(x: Int): Int = x * 2
fn addOne(x: Int): Int = x + 1
fn clamp(x: Int, max: Int): Int = minOf(x, max)

println(5 |> double |> addOne)
println(5 |> double |> clamp(8))     // clamp(10, 8)
Output
11
8

Every built-in function works in pipes, including those called on a value like filter and map:

let result = (1..20)
    |> filter { it % 3 == 0 }
    |> map { it * it }
    |> take(3)
println(result)
Output
[9, 36, 81]

#Extension functions

An extension function adds a function to an existing type, even a built-in one. Inside it, this is the value it's called on (and its members can be used without this.):

fn String.shout(): String = this.uppercase() + "!"
fn Int.isEven(): Bool = this % 2 == 0
fn List<Int>.secondOrZero(): Int = if size > 1 { this[1] } else { 0 }

println("hey".shout())
println(4.isEven())
println([7, 8, 9].secondOrZero())
println("pipes too" |> shout)
Output
HEY!
true
8
PIPES TOO!

A class's own methods win over extensions with the same name, and your extensions win over the built-in ones.

#Generic functions

Type parameters go in angle brackets after the name. Zyn works out what they are at each call:

fn firstOrDefault<T>(items: List<T>, default: T): T =
    if items.isEmpty() { default } else { items[0] }


println(firstOrDefault([3, 4], 0))
println(firstOrDefault(listOf<String>(), "none"))
Output
3
none