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.scalaWe define a function
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 ())
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.scalaBoth scripts provide the same output:
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 ())
HeartOfGold: ~ $ scala much closures2.scalaWhen the Scala interpreter with
11 21 22
12
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