Skip to content

Commit 11e7284

Browse files
committed
By Name Parameters
1 parent e8dd265 commit 11e7284

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

Functions/ByNameParameters.scala

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/**
2+
* By Name parameters are parameters that can be called by block and lazily evaluated.
3+
* By Name parameters are excellent for catching exception and cleaning up resources after you have done.
4+
*/
5+
6+
object ByNameParameters extends App
7+
{
8+
def byValue(x:Int)(y:Int) = {println("By Value:"); x + y}
9+
10+
def byFunction(x:Int)(y: () => Int) = {println("By Function:"); x + y()}
11+
12+
def byName(x:Int)(y: => Int) = {println("By Name:"); x + y}
13+
14+
val a = byValue(3){
15+
println("In ByValue call..");
16+
19
17+
} //this function will be evaluated first
18+
19+
val b = byFunction(3)(() => {println("In ByFunction Call.."); 19}) // This line will be evaluated lazily. after call to byFunction
20+
21+
val c = byName(3){
22+
println("In ByName call...");
23+
19
24+
} //This line will be evaluated lazily.
25+
26+
def divideSafely(f: =>Int):Option[Int] = {
27+
try
28+
{
29+
Some(f)
30+
}catch
31+
{
32+
case ae: ArithmeticException => None
33+
}
34+
35+
}
36+
37+
val d = divideSafely(
38+
{
39+
val x = 10
40+
val y = 5
41+
x / y
42+
43+
})
44+
45+
println("d = " + d)
46+
47+
val e = divideSafely(
48+
{
49+
val x = 10
50+
val y = 0
51+
x / y
52+
53+
})
54+
55+
println("e = " + e)
56+
57+
58+
}
59+
60+
/*
61+
Sample Output
62+
63+
In ByValue call..
64+
By Value:
65+
By Function:
66+
In ByFunction Call..
67+
By Name:
68+
In ByName call...
69+
d = Some(2)
70+
e = None
71+
72+
*/

0 commit comments

Comments
 (0)