Skip to content

Commit e944d5c

Browse files
committed
apply Method
methods as Infix Operators
1 parent 4a274d7 commit e944d5c

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed

Methods/EmployeeDesignWithApply.scala

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import java.time._
2+
3+
class Employee protected(val firstName:String, val lastName: String, val title:String, val hireDate:LocalDate)
4+
5+
object Employee
6+
{
7+
def apply(firstName:String, lastName:String, title:String) =
8+
new Employee(firstName, lastName, title, LocalDate.now)
9+
10+
11+
//if a method name is "apply", you dont have to explicitly call it.
12+
//apply can be used in classes and objects
13+
def apply(firstName:String, lastName:String, title:String, hireDate:LocalDate) =
14+
new Employee(firstName, lastName, title, hireDate)
15+
}
16+
17+
case class Department(name:String)
18+
19+
object EmployeeDesignWithApplyRunner extends App
20+
{
21+
val e1 = Employee("Bruce", "Wayne", "BatMan")
22+
println(e1.hireDate)
23+
24+
val department = Department.apply("Sports")
25+
val department2 = Department("Sports")
26+
println(department)
27+
println(department2)
28+
}
29+
30+
/**
31+
Sample Output
32+
33+
> scalac EmployeeDesignWithApply.scala
34+
35+
> scala EmployeeDesignWithApplyRunner
36+
2017-05-02
37+
Department(Sports)
38+
Department(Sports)
39+
**/

Methods/InfixOperators.scala

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Foo(x:Int)
2+
{
3+
def bar(y:Int) = x + y
4+
def baz(a:Int, b:Int) = x + a + b
5+
def bab(y:Int) = new Foo(x + y)
6+
def qux(y:Int) = new Foo(x + y)
7+
8+
}
9+
10+
object InfixOperatorRunner extends App
11+
{
12+
val foo = new Foo(10)
13+
println("foo.bar(5) = " + foo.bar(5))
14+
println("foo bar 5 = " + (foo bar 5 ))
15+
println("foo.baz(10, 14) = " + foo.baz(10, 14))
16+
println("foo baz (10, 14) = " + (foo baz (10, 14)))
17+
18+
//infix operators are similar to mathematical operators in scala
19+
//e.g.consider following examples
20+
println("3.+(10) = " + (3.+(10)))
21+
println("foo bar 4 + 19 = " + ((foo bar 4) + 19))
22+
23+
//chaining of infix operators
24+
// println(foo bab 4 bab 10 bab 19 bab (100 + 20) bar 40 + 300)
25+
println(foo qux 4 qux 10 qux 19 qux (100 + 19) bar 40 + 300)
26+
}
27+
28+
/**
29+
Sample Output
30+
> scalac InfixOperators.scala
31+
32+
> scala InfixOperatorRunner
33+
foo.bar(5) = 15
34+
foo bar 5 = 15
35+
foo.baz(10, 14) = 34
36+
foo baz (10, 14) = 34
37+
3.+(10) = 13
38+
foo bar 4 + 19 = 33
39+
502
40+
**/

0 commit comments

Comments
 (0)