Sunday, January 31, 2010

Herpes Virus And Escorts

Closures in

supported as functional language Scala higher-order functions (first-class functions) and functional outcomes ( Closures ). In the review of Closures in JavaFXScript I had already shown how there Closures are defined and used. How to program in Scala Closures now?
 / / closures1.scala 

def zaehlerMitStartwert (starting value: Int): (() => Int) = {var n = start value

def nplus1 (): Int = {n = n +1, n}
nplus1
}

val = next1 zaehlerMitStartwert (10)
val = next2 zaehlerMitStartwert (20)

println (next1 ()) println
(next2 ()) println
(next2 ()) println
(next1 ())
We define a function zaehlerMitStartwert () that the over starting value as the parameter gets Int. Return of this function is a function that has no parameters and returns an int value.

within the outer function, we create a counter variable n to because of the transfer parameters starting value is immutable. Then we define a nested function nplus1 () , the n to the count variable one better one and returns as the ultimate expression of the function, the incremented n . Here, instead of the function of accounts - the binding of the variable n , which is defined as a local variable in the outer function. As a final expression in the outer function, we give the function nplus1 as a result.

The whole is a bit shorter and "functional" when the inner function does not explicitly defined, but as a final expression of the outer function like writing down an appropriate function literal:
 / / closures2.scala 

def zaehlerMitStartwert (starting value: Int ) = {var n = start value

() => {N = n +1, n}}


val = next1 zaehlerMitStartwert (10)
val = next2 zaehlerMitStartwert (20)

println (next1 ()) println
(next2 ()) println
(next2 ()) println
(next1 ())
Both scripts provide the same output:
 HeartOfGold: ~ $ scala much closures2.scala 

11 21 22

12
When the Scala interpreter with scala-savecompiled closures2 . scala calls, you get a JAR archive, where you can look at the generated Java bytecode files. In this case, four class files are generated.

0 comments:

Post a Comment