SlideShare a Scribd company logo
   Introducing Functional 
                      Objects


                                         Ruchi Jindal
                                      Software Consultant     
                                          Knoldus
What is Functional Programming


    It must be true: x == y   <==> f( x ) == f( y )


 In a functional language, a function is a value of the same status as, say,
an integer or a string.
Eg :1+2 OR Matrix1+ Matrix2


 You can pass functions as arguments to other functions & return them as
results from functions,or store them in variables.


 Define a function inside another function.


 Define functions without giving them a name.
What is Functional Object

 Functional objects is a objects that do not have any mutable state.


 Immutable objects not have complex state spaces that change
over time.


 We can pass immutable objects whereas we may need to make
defensive copies of mutable objects before passing them to other
code.


 No thread can change the state of an immutable object.
Function Currying in Scala

Currying is the technique of transforming a function that takes multiple
arguments into a function that takes a single argument.
Eg:

def add(x:Int, y:Int) = x + y

And after currying:

def add(x:Int) = (y:Int) => x + y
Add(1)(2) // 3

The second example redefines the add method so that it takes only a single
Int as a parameter and returns a functional (closure) as a result.
Partials v/s Currying
            Partial Function                                 Currying

def add(x:Int, y:Int, z:Int) = x + y + z   def add(x:Int, y:Int, z:Int) = x + y + z
val addFive = add(5, _:Int, _:Int)         val addFive = (a:Int, b:Int) => add(5, a, b)
Scala> addFive(3, 1) //9                   Scala> addFive(3, 1)     // 9
Constructing a Rational Object

class Rational(n: Int, d: Int)

here n & d are class parameters.

The Scala compiler will gather up these two class parameters and create a
primary constructor that takes the same two parameters.

scala> new Rational(1, 2)
res0: Rational = Rational@90110a
Reimplementing the toString method
We can override the default implementation by adding a method toString to
class Rational, like this:

class Rational(n: Int, d: Int) {
override def toString = n +"/"+ d
}

scala> val x = new Rational(1, 3)
x: Rational = 1/3
Checking preconditions
class Rational(n: Int, d: Int) {
require(d != 0)
override def toString = n +"/"+ d
}

The require method takes one boolean parameter.

require will prevent the object from being constructed by throwing an
IllegalArgumentException.
Adding Fields
//won't compile

class Rational(n: Int, d: Int) {
require(d != 0)
override def toString = n +"/"+ d
def add(that: Rational): Rational =
new Rational(n * that.d + that.n * d, d * that.d)
}

Here add method is the field

that.n or that.d, because that does not refer to the Rational
object on which add was invoked
//here is the correct example


class Rational(n: Int, d: Int) {
  require(d != 0)
  val numer: Int = n
  val denom: Int = d
  override def toString = numer + "/" + denom
  def add(that: Rational): Rational =
    new Rational(
      numer * that.denom + that.numer * denom,
      denom * that.denom)
}
scala> val rational = new Rational(1, 2)
rational: Rational = ½

scala> rational.numer
res1: Int = 1

scala> rational.denom
res2: Int = 2

scala> val oneHalf = new Rational(1, 2)
oneHalf: Rational = ½

scala> val twoThirds = new Rational(2, 3)
twoThirds: Rational = 2/3

scala> oneHalf add twoThirds          // oneHalf.add(twoThirds)
res3: Rational = 7/6
Self references
this refers to the self reference .

def add(that: Rational): Rational =
  new Rational( this.numer * that.denom + that.numer * this.denom,
    this.denom * that.denom)

scala> val oneHalf = new Rational(1, 2)
oneHalf: Rational = ½
scala> val twoThirds = new Rational(2, 3)
twoThirds: Rational = 2/3
scala> oneHalf add twoThirds
res3: Rational = 7/6
Auxiliary constructors

In Scala, constructors other than the primary constructor are called
auxiliary constructors.

Auxiliary constructors in Scala start with def this(...)

class Rational(n: Int, d: Int) {
def this(n: Int) = this(n, 1)                // auxiliary constructor
}

scala> val rational = new Rational(3)
rational: Rational = 3/1
Private fields and methods

class Rational(n: Int, d: Int) {

private val g = gcd(n.abs, d.abs)
val numer = n / g
val denom = d / g
def this(n: Int) = this(n, 1)

override def toString = numer +"/"+ denom

private def gcd(a: Int, b: Int): Int =
if (b == 0) a else gcd(b, a % b)
}
scala> new Rational(50,10)
res1: Rational = 5/1
Defining operators

We can write operation(+,*,-,/.....) on functional object as same as integer
object like

eg def + (that: Rational): Rational =
new Rational(numer * that.denom + that.numer * denom,
denom * that.denom)

scala> onehalf + twothird     //onehalf.+(twothird)
res1: Rational = 7/6

It is same as 1+2 or 1*2
Scala’s also follows the rules for operator precedence.
Eg:
x + x * y will execute as x + (x * y), not (x + x) * y:

scala>oneHalf + oneHalf * twoThirds
res1: Rational = 5/6

The above expression will evaluated as

oneHalf.+(oneHalf.*(twoThirds))
Method overloading

scala>oneThird + 2       // oneThird.+(2)
res1: Rational = 7/3

def + (that: Rational): Rational =
new Rational(numer * that.denom + that.numer * denom,
denom * that.denom
)

def + (i: Int): Rational =
new Rational(numer + i * denom, denom)
Implicit conversions

OneHalf * 2          // compile because it convert into OneHalf.*(2)

2 * OneHalf         // won't compile because it convert into 2.*(OneHalf)

To resolve this implicit conversion is used.

scala> implicit def intToRational(x: Int) = new Rational(x)

This defines a conversion method from Int to Rational.

scala> val r = new Rational(2,3)
r: Rational = 2/3
scala> 2 * r
res1: Rational = 4/3
Object Equality

 The == equality is reserved in Scala for the“natural” equality of each type.

 For value types, == is value comparison.

 We can redefine the behavior of == for new types by overriding the equals
method,which is always inherited from class Any.

 It is not possible to override == directly, as it is defined as a final method in
class Any.

 If two objects are equal according to the equals method, then calling the
hashCode method on each of the two objects must produce the same integer
result.

Eg:
var r1=new Rational(1,2)
var r2=new Rational(-1,2)
scala> r1 equals r2     //false
Example of equality on Rational
             class
override def equals(other: Any): Boolean =
    other match {
      case that: Rational =>
        (that canEqual this) &&
          numer == that.numer &&
          denom == that.denom
      case _ => false
    }

 def canEqual(other: Any): Boolean =
   other.isInstanceOf[Rational]
 override def hashCode: Int =
   41 * (
     41 + numer) + denom
Functional object

More Related Content

What's hot

Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
Sandip Kumar
 
Data structures in scala
Data structures in scalaData structures in scala
Data structures in scala
Meetu Maltiar
 

What's hot (20)

C# p8
C# p8C# p8
C# p8
 
Google06
Google06Google06
Google06
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
 
Linq and lambda
Linq and lambdaLinq and lambda
Linq and lambda
 
Introducing scala
Introducing scalaIntroducing scala
Introducing scala
 
Intro to functional programming - Confoo
Intro to functional programming - ConfooIntro to functional programming - Confoo
Intro to functional programming - Confoo
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Data Structures - Searching & sorting
Data Structures - Searching & sortingData Structures - Searching & sorting
Data Structures - Searching & sorting
 
Scala collections
Scala collectionsScala collections
Scala collections
 
Loops and functions in r
Loops and functions in rLoops and functions in r
Loops and functions in r
 
Data structures in scala
Data structures in scalaData structures in scala
Data structures in scala
 
The Functional Programming Triad of fold, scan and iterate
The Functional Programming Triad of fold, scan and iterateThe Functional Programming Triad of fold, scan and iterate
The Functional Programming Triad of fold, scan and iterate
 
Data structures arrays
Data structures   arraysData structures   arrays
Data structures arrays
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScript
 
Comparing Haskell & Scala
Comparing Haskell & ScalaComparing Haskell & Scala
Comparing Haskell & Scala
 
Scala for Java Developers
Scala for Java DevelopersScala for Java Developers
Scala for Java Developers
 
Refinement Types for Haskell
Refinement Types for HaskellRefinement Types for Haskell
Refinement Types for Haskell
 
The Ring programming language version 1.9 book - Part 98 of 210
The Ring programming language version 1.9 book - Part 98 of 210The Ring programming language version 1.9 book - Part 98 of 210
The Ring programming language version 1.9 book - Part 98 of 210
 
Lecture 02: Preliminaries of Data structure
Lecture 02: Preliminaries of Data structureLecture 02: Preliminaries of Data structure
Lecture 02: Preliminaries of Data structure
 
Java Tutorial Lab 8
Java Tutorial Lab 8Java Tutorial Lab 8
Java Tutorial Lab 8
 

Viewers also liked (6)

Introduction To Outlook Express
Introduction To Outlook ExpressIntroduction To Outlook Express
Introduction To Outlook Express
 
Microsoft Outlook 2007
Microsoft Outlook 2007Microsoft Outlook 2007
Microsoft Outlook 2007
 
Microsoft outlook 2010
Microsoft outlook 2010Microsoft outlook 2010
Microsoft outlook 2010
 
Getting started with Outlook
Getting started with OutlookGetting started with Outlook
Getting started with Outlook
 
Basic of MS Outlook
Basic of MS OutlookBasic of MS Outlook
Basic of MS Outlook
 
Outlook Presentation
Outlook PresentationOutlook Presentation
Outlook Presentation
 

Similar to Functional object

Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional Programming
Eelco Visser
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
Eelco Visser
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
Sandip Kumar
 
TI1220 Lecture 8: Traits & Type Parameterization
TI1220 Lecture 8: Traits & Type ParameterizationTI1220 Lecture 8: Traits & Type Parameterization
TI1220 Lecture 8: Traits & Type Parameterization
Eelco Visser
 
I just need answers for all TODO- I do not need any explanation or any.pdf
I just need answers for all TODO- I do not need any explanation or any.pdfI just need answers for all TODO- I do not need any explanation or any.pdf
I just need answers for all TODO- I do not need any explanation or any.pdf
MattU5mLambertq
 
I just need answers for all TODO- I do not need any explanation or any (1).pdf
I just need answers for all TODO- I do not need any explanation or any (1).pdfI just need answers for all TODO- I do not need any explanation or any (1).pdf
I just need answers for all TODO- I do not need any explanation or any (1).pdf
MattU5mLambertq
 

Similar to Functional object (20)

Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional Programming
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
JBUG 11 - Scala For Java Programmers
JBUG 11 - Scala For Java ProgrammersJBUG 11 - Scala For Java Programmers
JBUG 11 - Scala For Java Programmers
 
Spark workshop
Spark workshopSpark workshop
Spark workshop
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskell
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskell
 
The Ring programming language version 1.6 book - Part 33 of 189
The Ring programming language version 1.6 book - Part 33 of 189The Ring programming language version 1.6 book - Part 33 of 189
The Ring programming language version 1.6 book - Part 33 of 189
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
 
Introduction to R
Introduction to RIntroduction to R
Introduction to R
 
Scala Bootcamp 1
Scala Bootcamp 1Scala Bootcamp 1
Scala Bootcamp 1
 
Statistics lab 1
Statistics lab 1Statistics lab 1
Statistics lab 1
 
Scala cheatsheet
Scala cheatsheetScala cheatsheet
Scala cheatsheet
 
TI1220 Lecture 8: Traits & Type Parameterization
TI1220 Lecture 8: Traits & Type ParameterizationTI1220 Lecture 8: Traits & Type Parameterization
TI1220 Lecture 8: Traits & Type Parameterization
 
I just need answers for all TODO- I do not need any explanation or any.pdf
I just need answers for all TODO- I do not need any explanation or any.pdfI just need answers for all TODO- I do not need any explanation or any.pdf
I just need answers for all TODO- I do not need any explanation or any.pdf
 
I just need answers for all TODO- I do not need any explanation or any (1).pdf
I just need answers for all TODO- I do not need any explanation or any (1).pdfI just need answers for all TODO- I do not need any explanation or any (1).pdf
I just need answers for all TODO- I do not need any explanation or any (1).pdf
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 
Scala by Luc Duponcheel
Scala by Luc DuponcheelScala by Luc Duponcheel
Scala by Luc Duponcheel
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
 

Recently uploaded

Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Peter Udo Diehl
 

Recently uploaded (20)

WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024
 
IESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIESVE for Early Stage Design and Planning
IESVE for Early Stage Design and Planning
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
AI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekAI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří Karpíšek
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2
 
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
 
Introduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationIntroduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG Evaluation
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1
 
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 

Functional object

  • 1.    Introducing Functional  Objects  Ruchi Jindal                                       Software Consultant    Knoldus
  • 2. What is Functional Programming  It must be true: x == y <==> f( x ) == f( y )  In a functional language, a function is a value of the same status as, say, an integer or a string. Eg :1+2 OR Matrix1+ Matrix2  You can pass functions as arguments to other functions & return them as results from functions,or store them in variables.  Define a function inside another function.  Define functions without giving them a name.
  • 3. What is Functional Object  Functional objects is a objects that do not have any mutable state.  Immutable objects not have complex state spaces that change over time.  We can pass immutable objects whereas we may need to make defensive copies of mutable objects before passing them to other code.  No thread can change the state of an immutable object.
  • 4. Function Currying in Scala Currying is the technique of transforming a function that takes multiple arguments into a function that takes a single argument. Eg: def add(x:Int, y:Int) = x + y And after currying: def add(x:Int) = (y:Int) => x + y Add(1)(2) // 3 The second example redefines the add method so that it takes only a single Int as a parameter and returns a functional (closure) as a result.
  • 5. Partials v/s Currying Partial Function Currying def add(x:Int, y:Int, z:Int) = x + y + z def add(x:Int, y:Int, z:Int) = x + y + z val addFive = add(5, _:Int, _:Int) val addFive = (a:Int, b:Int) => add(5, a, b) Scala> addFive(3, 1) //9 Scala> addFive(3, 1) // 9
  • 6. Constructing a Rational Object class Rational(n: Int, d: Int) here n & d are class parameters. The Scala compiler will gather up these two class parameters and create a primary constructor that takes the same two parameters. scala> new Rational(1, 2) res0: Rational = Rational@90110a
  • 7. Reimplementing the toString method We can override the default implementation by adding a method toString to class Rational, like this: class Rational(n: Int, d: Int) { override def toString = n +"/"+ d } scala> val x = new Rational(1, 3) x: Rational = 1/3
  • 8. Checking preconditions class Rational(n: Int, d: Int) { require(d != 0) override def toString = n +"/"+ d } The require method takes one boolean parameter. require will prevent the object from being constructed by throwing an IllegalArgumentException.
  • 9. Adding Fields //won't compile class Rational(n: Int, d: Int) { require(d != 0) override def toString = n +"/"+ d def add(that: Rational): Rational = new Rational(n * that.d + that.n * d, d * that.d) } Here add method is the field that.n or that.d, because that does not refer to the Rational object on which add was invoked
  • 10. //here is the correct example class Rational(n: Int, d: Int) { require(d != 0) val numer: Int = n val denom: Int = d override def toString = numer + "/" + denom def add(that: Rational): Rational = new Rational( numer * that.denom + that.numer * denom, denom * that.denom) }
  • 11. scala> val rational = new Rational(1, 2) rational: Rational = ½ scala> rational.numer res1: Int = 1 scala> rational.denom res2: Int = 2 scala> val oneHalf = new Rational(1, 2) oneHalf: Rational = ½ scala> val twoThirds = new Rational(2, 3) twoThirds: Rational = 2/3 scala> oneHalf add twoThirds // oneHalf.add(twoThirds) res3: Rational = 7/6
  • 12. Self references this refers to the self reference . def add(that: Rational): Rational = new Rational( this.numer * that.denom + that.numer * this.denom, this.denom * that.denom) scala> val oneHalf = new Rational(1, 2) oneHalf: Rational = ½ scala> val twoThirds = new Rational(2, 3) twoThirds: Rational = 2/3 scala> oneHalf add twoThirds res3: Rational = 7/6
  • 13. Auxiliary constructors In Scala, constructors other than the primary constructor are called auxiliary constructors. Auxiliary constructors in Scala start with def this(...) class Rational(n: Int, d: Int) { def this(n: Int) = this(n, 1) // auxiliary constructor } scala> val rational = new Rational(3) rational: Rational = 3/1
  • 14. Private fields and methods class Rational(n: Int, d: Int) { private val g = gcd(n.abs, d.abs) val numer = n / g val denom = d / g def this(n: Int) = this(n, 1) override def toString = numer +"/"+ denom private def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b) } scala> new Rational(50,10) res1: Rational = 5/1
  • 15. Defining operators We can write operation(+,*,-,/.....) on functional object as same as integer object like eg def + (that: Rational): Rational = new Rational(numer * that.denom + that.numer * denom, denom * that.denom) scala> onehalf + twothird //onehalf.+(twothird) res1: Rational = 7/6 It is same as 1+2 or 1*2
  • 16. Scala’s also follows the rules for operator precedence. Eg: x + x * y will execute as x + (x * y), not (x + x) * y: scala>oneHalf + oneHalf * twoThirds res1: Rational = 5/6 The above expression will evaluated as oneHalf.+(oneHalf.*(twoThirds))
  • 17. Method overloading scala>oneThird + 2 // oneThird.+(2) res1: Rational = 7/3 def + (that: Rational): Rational = new Rational(numer * that.denom + that.numer * denom, denom * that.denom ) def + (i: Int): Rational = new Rational(numer + i * denom, denom)
  • 18. Implicit conversions OneHalf * 2 // compile because it convert into OneHalf.*(2) 2 * OneHalf // won't compile because it convert into 2.*(OneHalf) To resolve this implicit conversion is used. scala> implicit def intToRational(x: Int) = new Rational(x) This defines a conversion method from Int to Rational. scala> val r = new Rational(2,3) r: Rational = 2/3 scala> 2 * r res1: Rational = 4/3
  • 19. Object Equality  The == equality is reserved in Scala for the“natural” equality of each type.  For value types, == is value comparison.  We can redefine the behavior of == for new types by overriding the equals method,which is always inherited from class Any.  It is not possible to override == directly, as it is defined as a final method in class Any.  If two objects are equal according to the equals method, then calling the hashCode method on each of the two objects must produce the same integer result. Eg: var r1=new Rational(1,2) var r2=new Rational(-1,2) scala> r1 equals r2 //false
  • 20. Example of equality on Rational class override def equals(other: Any): Boolean = other match { case that: Rational => (that canEqual this) && numer == that.numer && denom == that.denom case _ => false } def canEqual(other: Any): Boolean = other.isInstanceOf[Rational] override def hashCode: Int = 41 * ( 41 + numer) + denom