imperative style : if code ontains any vars
functional style : it contains only vals
imperative style:
def printArgs(args: Array[String])):Unit ={
var i =0
while (i < args.length) {
println(args(i))
i +=1
}
}
your can transform this bit of code into a more functional style by getting rid of the var, for example, like this.
def printArgs(args: Array[String]): Unit = {
for( arg <- args="" div="" nbsp="">
->
println(arg)
}
or this:
def printArgs(args: Array[String]: Unit = {
args.foreach(println)
}
Benefit of programming with fewer vars.
- The refactoryed(more functional) code is clearer.
- More concise
- less error-prone than the original(more imperative) code.
The telltale sign of a function with side effects is that its result type is Unit.
If a function isn't returning any interesting value, which is what a result type of Unit means, the only way that function can make a difference in the world is through some kind of side effect.
댓글 없음:
댓글 쓰기