An anonymous function can also take on a different look by taking out the brackets:
Function taking another function as a parameter.
Function taking another function as a parameter. Helps in composing functions.
Hint: a map method applies the function to each element of a list.
We can take that closure and throw it into a method and it will still hold the environment:
isInstanceOf
is the same as instanceof
in java, but in this case the parameter types can be *blanked out* using existential types with a single underline, since parameter types are unknown at runtime.
Here the only variable used in the function body, i * 10
, is i
, which is defined as a parameter to the function.
Here the only variable used in the function body, i * 10
, is i
, which is defined as a parameter to the function.
val multiplier = (i:Int) => i * 10
A closure is a function which maintains a reference to one or more variables outside of the function scope (it "closes over" the variables). Scala will detect that you are using variables outside of scope and create an object instance to hold the shared variables.
Meet lambda.
Meet lambda. Scala provides a relatively lightweight syntax for defining anonymous functions. Anonymous functions in source code are called function literals and at run time, function literals are instantiated into objects called function values.
Scala supports first-class functions, which means you can express functions in function literal syntax, i.e. (x: Int) => x + 1
, and those functions can be represented by objects, which are called function values.
Function returning another function using an anonymous function:
Function returning another function:
The parameterless execute method has been deprecated and will be removed in a future version of ScalaTest. Please invoke execute with empty parens instead: execute().
The trap method is no longer needed for demos in the REPL, which now abreviates stack traces, and will be removed in a future version of ScalaTest