SlideShare uma empresa Scribd logo
1 de 21
   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

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Destaque (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
 

Semelhante a 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
 

Semelhante a 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
 

Último

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Último (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 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