When programs get larger, you need some way to divide them into smaller, more manageable pieces. For dividing up control flow, Scala offers an approach familiar to all experienced programmers: divide the code into functions.
def
main(args: Array[String]) {
a) We can assign an object to a function à function object.
b) We can
assign one function object to another function object.
c) Function
object can be passed as a parameter to another function / method.
d)
Functions object are returned from a method or
function.
An Example: def add is a function.
Another Example:
Def doubler is a
function.
Doubler is assigning to
an object called myDoubler.
We
need to give datatypes for both Input and output of a function to get the
results.
In above case, datatype is Int.
Thus a Scala function should only transform its inputs into its
outputs and should have no (hidden) side effects. That is, it should not change
the state of the system nor should it be involved in any state-based behaviour.
Some
Functional Examples:
Type scala> z. (tab)
Type scala> z.+ (tab)
String Interpolation (f):
String Interpolation is defining a
string literal with one or more placeholders, these placeholders are to be replaced
with variables or expressions while the final compilation of the result.
Scala programming languages support string
interpolation and multiple methods to process the string literals easily.
A pure function is a function that does not have a dependency on i/o and other values that are out of the function's scope and depending only on the values that are passed in parameters and algorithm (operations) of the function.
E.g.:- isEmpty(), sqrt(), etc.
Closures in Scala are a special type of functions. Closures use one or more values that are not declared in the function to give the final output. This means their return value is dependent on values that are declared outside the function ( i.e. declared neither in the arguments nor in function body).
Anonymous function: Function without a name uses function literal syntax (=>) instead of equal (=) syntax. We can assign this function to a variable and call it using a variable.
e.g.:- scala> def doubler(i:int):int => {return i * 2)
scala> val d = (i:Int) => { i*2 } :Int
d: Int => Int = <function>
scala> d(3)
res1: Int = 6.
No comments:
Post a Comment