What does the community think about purity indicator in functions like “!” in ruby.
For example we may use:
This have two major benefits:
The first one is that developpers will have a better readability of the code.
For example we can force the operator
plus() to be pure and accept that the operator
plusAssign!() to be unpure.
As the code
val list = listOf(1, 2) + listOf(3) // [1, 2].plus() val mList = mutableList(1, 2) // mList = [1, 2] mList += 3 // mList.plusAssign!()
Here we can see that mList should be modified by the plusAssign! but we can also see that plus() do not authorized to modify [1, 2].
The second benefit for this kind of keyword is to improve the performance of the code when optimization.
A function call is used only if the function is not pure or the returned value of the value is used.
fun square(x: Int): Int = x * x val x = 10 // x is used by square(x) val sqrtX = square(x) // here square is a pure function and his result is used later println!(sqrtX) // println should have a side effect so we cannot determined if sqrtX is used for real or not
Here the compiler execute all the program
fun square(x: Int): Int = x * x val x = 10 val sqrtX = square(x) foo(sqrtX)
In the second example, we see that foo is pure so we can replace the call
foo(sqrtX) with his result
fun square(x: Int): Int = x * x val x = 10 val sqrtX = square(x) // replaced by Unit
here we can see that sqrtX is not used anymore so we can suppress the call to square(x), etc. At the end we see that the program execute nothing.