Pure functions

A pure function is a function without any side effects. Take the following function, for example:

fun sayHello() {
println("Hello")
}

How do you test to see whether "Hello" is indeed printed? The task is not as simple as it seems, as we'll need some means to capture the standard output, the same console where we usually see stuff printed. 

Compare it to the following function:

fun hello() = "Hello"

The following function doesn't have any side effects. That makes it a lot easier to test:

fun testHello(): Boolean {
return "Hello" == hello()
}

Does the hello() function look a bit meaningless to your eyes? That's actually one of the properties of pure functions. Their invocation could be replaced by their result (if we knew all their results, that is). This is often called referential transparency.

Not every function written in Kotlin is pure:

fun <T> removeFirst(list: MutableList<T>): T {
return list.removeAt(0)
}

If we call the function twice on the same list, it will return different results:

val list = mutableListOf(1, 2, 3)

println(removeFirst(list)) // Prints 1
println(removeFirst(list)) // Prints 2

Try this one:

fun <T> withoutFirst(list: List<T>): T {
return ArrayList(list).removeAt(0)
}

Now our function is totally predictable, no matter how many times we invoke it:

val list = mutableListOf(1, 2, 3)

println(withoutFirst(list)) // It's 1
println(withoutFirst(list)) // Still 1

As you can see, we used an immutable interface this time, List<T>, which helps us by preventing even the possibility of mutating our input. Together with immutable values from the previous section, pure functions provide a very strong tool that allows easier testing by providing predictable results and parallelization of our algorithms.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.34.226