Skip to content

Instantly share code, notes, and snippets.

@exallium
Created February 10, 2017 15:12
Show Gist options
  • Save exallium/60ec29a8d7631f7b6189d5fa986eb25b to your computer and use it in GitHub Desktop.
Save exallium/60ec29a8d7631f7b6189d5fa986eb25b to your computer and use it in GitHub Desktop.
// In Kotlin, Functions are "first class" members. This means that you can pass them around.
// For example, a function can be expressed utilizing lambda syntax like so:
val f1: (Int, Int) -> Int = { a, b -> a + b }
// this can be read as follows
// the value (val) f1 is a function which takes two ints (Int, Int) and returns (->) an Int.
// the funciton body has two parameters a, b which it adds together.
// In a lambda expression like this, the result of the last line is also the return statement
// The exception is if the return type is Unit, in which case there is no return statement.
// We can then pass this value to a function parameter which accepts it. For example:
(1..5).reduce(f1)
// Reduce has a single parameter with type (Int, Int) -> Int, which means it takes a function which
// accepts two integers and returns an integer. We can thus pass f1 to this since the types line up.
// We could also declare our own lambda on the fly for reduce, and Kotlin lets us ditch the parens.
(1..5).reduce { a, b -> a * b }
// We could also pass a function reference:
fun f2(a: Int, b: Int): Int { return a + b }
(1..5).reduce(::f2)
// In this example f2 is declared outside of any class instance. ::f2 is a reference to the function f2. Since f2
// takes two ints and produces an int, it's reference is of type (Int, Int) -> Int, which matches our requirement.
// Note that declaring a function to be utilized as a reference requires that you create it outside of a class instance.
// As far as I can tell, this is a limitation of the language. In these cases, you would opt for the lambda expression syntax.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment