concept int in category kotlin

appears as: Int, n Int
The Joy of Kotlin

This is an excerpt from Manning's book The Joy of Kotlin.

How would you test such a program? Of course, you see the bugs, so you’d start by fixing them before writing tests. But if you were the one responsible for these bugs, you wouldn’t see them. You’d instead want to test the implementation for limit values. The two parameters being an integer and a list, you’d probably want to test 0 as the int parameter or an empty list. The first condition would cause a java.lang.ArithmeticException: / by zero exception. The second condition would produce a result of 0.

The div function working on Int isn’t a pure function because it’ll throw an exception if the divisor is 0:

fun div(a: Int, b: Int): Int = a / b

To make div a pure function, you could test the second parameter and return a value if it’s null. It would have to be an Int, so it would be difficult to find a meaningful value, but that’s another problem. The div function working on doubles is a pure function because dividing by 0.0 won’t throw an exception, but will return Infinity, which is an instance of Double:

In this syntax, (Int) is the type of the argument, and (Int) -> Int is the type of the return value. To remember how the -> symbol associates, you can think of this as if there were parentheses around the return value so it’s equivalent to

(Int) -> ((Int) -> Int)

The argument type is Int and the return type is a function taking an argument of type Int, and returning an Int.