SlideShare a Scribd company logo
OPERATOR OVERLOADING
IN SCALA
Joey Gibson
First Things First
   Working with Java since 1996
   Playing with Scala for not-quite-a-year

   Originally a blog post on joeygibson.com
   See the original at http://bit.ly/wNvAl
   Based on example from Programming Scala, by
    Venkat Subramaniam
What Is Operator Overloading?
   A language facility that allows developers to define
    behavior for symbols like +, -, / for their own
    classes, mimicking built-in operators
   C++, Smalltalk, Ruby, lots of others have it
   Java does not have it
     Except + for String concatenation
     BigDecimal, BigInteger, etc. would be nicer to use with
      operators
The Basics
   Technically, Scala does not have operator
    overloading
     Operatorsare just methods
     Any method taking 0/1 argument can be called as an
      operator
         foo doSomething “x”    is the same as foo.doSomething(“x”)
         foo + 23   is the same as foo.+(23)
   You can define both binary and unary operators
     Only +, -, ~ and ! can be used as unary operators
     As with binary operators, it’s just a method and
         -foo   is the same as foo.unary_-
What About Precedence?
   Scala looks at the first character of the operator
    name
       All other special chars
       */%
       +-
       :
       =!
       <>
       &
       ^
       |
       All letters
       All assignment operators
Operator Naming
   Typically, you would use arithmetic operator
    symbols, but you don’t have to
   Since operators are just methods, you can use non-
    standard characters
     Δ,λ, γ, Ω, etc.
     Neat/useful, but use sparingly, unless it makes your
      code easier to read and/or maintain
   If the last character in an operator name is a colon,
    that method associates to the right
Complex.scala
package com.joeygibson.oopres

class Complex(val real: Int, val imaginary: Int) {
  def +(operand: Complex): Complex = {
    new Complex(real + operand.real, imaginary + operand.imaginary)
  }

    def *(operand: Complex): Complex = {
      new Complex(real * operand.real - imaginary * operand.imaginary,
                  real * operand.imaginary + imaginary * operand.real)
    }

    override def toString() = {
      real + (if (imaginary < 0) "" else "+") + imaginary + "i"
    }
}
ComplexTest.scala
package com.joeygibson.oopres


import org.junit.runner.RunWith
import org.scalatest.FlatSpec
import org.scalatest.matchers.ShouldMatchers
import org.scalatest.junit.JUnitRunner


@RunWith(classOf[JUnitRunner])
class ComplexTest extends FlatSpec with ShouldMatchers {
    "A Complex" should "sum up to 4-9i" in {
      val c1 = new Complex(1, 2)
        val c2 = new Complex(2, -3)
        val c3 = c1 + c2


        val res = c1 + c2 * c3

        res.toString should equal ("4-9i")
    }
}
Interesting Naming Examples
package com.joeygibson.oopres

import org.apache.commons.lang.StringUtils

class Fragment(val text: String) {
  override def toString = text

    def Δ(other: Fragment): Fragment = {
      val diff = StringUtils.difference(text, other.text)

        new Fragment(diff)
    }

    def ::(other: Fragment): Fragment = {
      new Fragment(text + " || " + other.text)
    }
}
Testing Interesting Names
package com.joeygibson.oopres


@RunWith(classOf[JUnitRunner])
class FragmentTest extends FlatSpec with ShouldMatchers {
    it should "return proper differences" in {
        val f0 = new Fragment("Scala is groovy")
        val f1 = new Fragment("Scala is cool")


        val diff = f0 Δ f1


        diff.toString should equal("cool")
    }


    it should "concatenate properly" in {
        val f0 = new Fragment("First Fragment")
        val f1 = new Fragment("Second Fragment")


        val f2 = f0 :: f1


        f2.toString should equal ("Second Fragment || First Fragment")
    }
}
You Can Even Get Silly…
package com.joeygibson.oopres

class Absurdity(val text: String) {
  def //(other: Absurdity) = {
       new Absurdity(text + ", " + other.text)
   }

    def //(other: Absurdity) = {
         new Absurdity(other.text + ", " + text)
     }

    override def toString = text
}
Testing the Silliness
package com.joeygibson.oopres


@RunWith(classOf[JUnitRunner])
class AbsurdityTest extends FlatSpec with ShouldMatchers {
    it should "do something absurd" in {
        val a = new Absurdity("foo")
        val b = new Absurdity("bar")


        val c = a // b


        c.toString should equal ("foo, bar")
    }


    it should "do something equally absurd" in {
        val a = new Absurdity("foo")
        val b = new Absurdity("bar")


        val c = a // b


        c.toString should equal ("bar, foo")
    }
}
Arguments of Different Types
   Define multiple versions of method, taking different
    types
   Use Implicit conversions
Multiple Defs of Operator
package com.joeygibson.oopres


class Complex2(val real: Int, val imaginary: Int) {
    def +(operand: Complex2): Complex2 = {
        new Complex2(real + operand.real, imaginary + operand.imaginary)
    }


    def +(operand: Int): Complex2 = this + new Complex2(operand, 0)


    def *(operand: Complex2): Complex2 = {
        new Complex2(real * operand.real - imaginary * operand.imaginary,
                   real * operand.imaginary + imaginary * operand.real)
    }


    def *(operand: Int): Complex2 = this * new Complex2(operand, 1)


    def unary_- = new Complex2(-real, imaginary)


    override def toString() = {
        real + (if (imaginary < 0) "" else "+") + imaginary + "i"
    }
}
Testing Multiple Defs
package com.joeygibson.oopres

@RunWith(classOf[JUnitRunner])
class Complex2Test extends FlatSpec with ShouldMatchers {
  it should "convert int to Complex2" in {
    val c = new Complex2(1, 2)
    val d = c + 23

         d.toString should equal ("24+2i")
     }

//       it should "convert int to Complex2, reversed" in {
//         val c = new Complex2(1, 2)
//         val d: Complex2 = 23 + c
//
//           d.toString should equal ("24+2i")
//       }
}
Implicit Conversions
   The implicit function must be in scope
   It can live in the companion object of either class
    under consideration

   Be careful with implicits, especially when using
    common types
Implicit Conversions
package com.joeygibson.oopres


object Complex3 {
    implicit def intToComplex3(anInt: Int): Complex3 = new Complex3(anInt, 0)
}


class Complex3(val real: Int, val imaginary: Int) {
    def +(operand: Complex3): Complex3 = {
        new Complex3(real + operand.real, imaginary + operand.imaginary)
    }


    def *(operand: Complex3): Complex3 = {
        new Complex3(real * operand.real - imaginary * operand.imaginary,
                   real * operand.imaginary + imaginary * operand.real)
    }


    def unary_- = new Complex3(-real, imaginary)


    override def toString() = {
        real + (if (imaginary < 0) "" else "+") + imaginary + "i"
    }
}
Testing Implicits
package com.joeygibson.oopres

@RunWith(classOf[JUnitRunner])
class Complex3Test extends FlatSpec with ShouldMatchers {
  it should "convert int to Complex3" in {
    val c = new Complex3(1, 2)
    val d = c + 23

        d.toString should equal ("24+2i")
    }

    it should "convert int to Complex3, reversed" in {
      import com.joeygibson.oopres.Complex3.intToComplex3
      val c = new Complex3(1, 2)
      val d: Complex3 = 23 + c

        d.toString should equal ("24+2i")
    }
}
Using Both
package com.joeygibson.oopres



object Complex4 {

    implicit def intToComplex4(anInt: Int): Complex4 = {

        printf("Implicitly converting to Complex4n")

        new Complex4(anInt, 0)

    }

}



class Complex4(val real: Int, val imaginary: Int) {

    def +(operand: Complex4): Complex4 = {

        new Complex4(real + operand.real, imaginary + operand.imaginary)

    }



    def +(operand: Int): Complex4 = this + new Complex4(operand, 0)



    def *(operand: Complex4): Complex4 = {

        new Complex4(real * operand.real - imaginary * operand.imaginary,

                   real * operand.imaginary + imaginary * operand.real)

    }



    def *(operand: Int): Complex4 = this * new Complex4(operand, 0)



    def unary_- = new Complex4(-real, imaginary)



    override def toString() = {

        real + (if (imaginary < 0) "" else "+") + imaginary + "i"

    }

}
You Can’t Use ++ as Prefix
package com.joeygibson.oopres


class MyNumber(private var num: Int) {


    def number: Int = num


    override def toString = num.toString


    def ++ = {
        val n = num
        num += 1


        new MyNumber(n)
    }


    def unary_++ = {
        num += 1


        this
    }
}
The First One Works, The Second…
package com.joeygibson.oopres


@RunWith(classOf[JUnitRunner])
class MyNumberTest extends FlatSpec with ShouldMatchers {
  it should "post increment" in {
     val x = new MyNumber(23)
     val z = x++


     z.number should equal (23)
     x.number should equal (24)
 }


//   it should "pre increment" in {
//     val x = new MyNumber(23)
//       val z = ++x
//
//       z.number should equal (24)
//       x.number should equal (24)
//   }
}
ἐγώ ἐιμι
   Email: joey@joeygibson.com
   Blog: http://joeygibson.com
     Original   post: http://bit.ly/wNvAl
   Twitter: @joeygibson
   Facebook: http://facebook.com/joeygibson

More Related Content

What's hot

Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with Scala
Denis
 
Scala Paradigms
Scala ParadigmsScala Paradigms
Scala Paradigms
Tom Flaherty
 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocaml
pramode_ce
 
Humble introduction to category theory in haskell
Humble introduction to category theory in haskellHumble introduction to category theory in haskell
Humble introduction to category theory in haskell
Jongsoo Lee
 
Introduction to scala
Introduction to scalaIntroduction to scala
Introduction to scala
Michel Perez
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardMario Fusco
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
Mario Fusco
 
List-based Monadic Computations for Dynamically Typed Languages (Python version)
List-based Monadic Computations for Dynamically Typed Languages (Python version)List-based Monadic Computations for Dynamically Typed Languages (Python version)
List-based Monadic Computations for Dynamically Typed Languages (Python version)
Wim Vanderbauwhede
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
Jonas Bonér
 
Hammurabi
HammurabiHammurabi
Hammurabi
Mario Fusco
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Mario Fusco
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
Maxim Novak
 
2 kotlin vs. java: what java has that kotlin does not
2  kotlin vs. java: what java has that kotlin does not2  kotlin vs. java: what java has that kotlin does not
2 kotlin vs. java: what java has that kotlin does not
Sergey Bandysik
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScript
tmont
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
Knoldus Inc.
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
daewon jeong
 
Composition birds-and-recursion
Composition birds-and-recursionComposition birds-and-recursion
Composition birds-and-recursion
David Atchley
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better Programmer
Mario Fusco
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
Tomer Gabel
 
A limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced RubyA limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced Ruby
Vysakh Sreenivasan
 

What's hot (20)

Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with Scala
 
Scala Paradigms
Scala ParadigmsScala Paradigms
Scala Paradigms
 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocaml
 
Humble introduction to category theory in haskell
Humble introduction to category theory in haskellHumble introduction to category theory in haskell
Humble introduction to category theory in haskell
 
Introduction to scala
Introduction to scalaIntroduction to scala
Introduction to scala
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
List-based Monadic Computations for Dynamically Typed Languages (Python version)
List-based Monadic Computations for Dynamically Typed Languages (Python version)List-based Monadic Computations for Dynamically Typed Languages (Python version)
List-based Monadic Computations for Dynamically Typed Languages (Python version)
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Hammurabi
HammurabiHammurabi
Hammurabi
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
 
2 kotlin vs. java: what java has that kotlin does not
2  kotlin vs. java: what java has that kotlin does not2  kotlin vs. java: what java has that kotlin does not
2 kotlin vs. java: what java has that kotlin does not
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScript
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
 
Composition birds-and-recursion
Composition birds-and-recursionComposition birds-and-recursion
Composition birds-and-recursion
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better Programmer
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
A limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced RubyA limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced Ruby
 

Similar to Operator Overloading In Scala

Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
Shaul Rosenzwieg
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
Ganesh Samarthyam
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
Prashant Kalkar
 
GeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetGeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheet
Jose Perez
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
Christian Baranowski
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for Kotlin
TechMagic
 
Groovy grails types, operators, objects
Groovy grails types, operators, objectsGroovy grails types, operators, objects
Groovy grails types, operators, objects
Husain Dalal
 
Kotlin
KotlinKotlin
Groovy closures
Groovy closuresGroovy closures
Groovy closures
Vijay Shukla
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
JyothiAmpally
 
Scala cheatsheet
Scala cheatsheetScala cheatsheet
Scala cheatsheet
Arduino Aficionado
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional ProgrammingEelco Visser
 
Lezione03
Lezione03Lezione03
Lezione03
robynho86
 
Extractors & Implicit conversions
Extractors & Implicit conversionsExtractors & Implicit conversions
Extractors & Implicit conversions
Knoldus Inc.
 
Hello kotlin | An Event by DSC Unideb
Hello kotlin | An Event by DSC UnidebHello kotlin | An Event by DSC Unideb
Hello kotlin | An Event by DSC Unideb
Muhammad Raza
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsEelco Visser
 
The Ring programming language version 1.4.1 book - Part 9 of 31
The Ring programming language version 1.4.1 book - Part 9 of 31The Ring programming language version 1.4.1 book - Part 9 of 31
The Ring programming language version 1.4.1 book - Part 9 of 31
Mahmoud Samir Fayed
 

Similar to Operator Overloading In Scala (20)

Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
GeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetGeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheet
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for Kotlin
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 
Functional object
Functional objectFunctional object
Functional object
 
Groovy grails types, operators, objects
Groovy grails types, operators, objectsGroovy grails types, operators, objects
Groovy grails types, operators, objects
 
Kotlin
KotlinKotlin
Kotlin
 
Groovy closures
Groovy closuresGroovy closures
Groovy closures
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
 
Scala cheatsheet
Scala cheatsheetScala cheatsheet
Scala cheatsheet
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional Programming
 
Lezione03
Lezione03Lezione03
Lezione03
 
Lezione03
Lezione03Lezione03
Lezione03
 
Extractors & Implicit conversions
Extractors & Implicit conversionsExtractors & Implicit conversions
Extractors & Implicit conversions
 
Hello kotlin | An Event by DSC Unideb
Hello kotlin | An Event by DSC UnidebHello kotlin | An Event by DSC Unideb
Hello kotlin | An Event by DSC Unideb
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
The Ring programming language version 1.4.1 book - Part 9 of 31
The Ring programming language version 1.4.1 book - Part 9 of 31The Ring programming language version 1.4.1 book - Part 9 of 31
The Ring programming language version 1.4.1 book - Part 9 of 31
 

Recently uploaded

By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website
Pixlogix Infotech
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Vladimir Iglovikov, Ph.D.
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 

Recently uploaded (20)

By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 

Operator Overloading In Scala

  • 2. First Things First  Working with Java since 1996  Playing with Scala for not-quite-a-year  Originally a blog post on joeygibson.com  See the original at http://bit.ly/wNvAl  Based on example from Programming Scala, by Venkat Subramaniam
  • 3. What Is Operator Overloading?  A language facility that allows developers to define behavior for symbols like +, -, / for their own classes, mimicking built-in operators  C++, Smalltalk, Ruby, lots of others have it  Java does not have it  Except + for String concatenation  BigDecimal, BigInteger, etc. would be nicer to use with operators
  • 4. The Basics  Technically, Scala does not have operator overloading  Operatorsare just methods  Any method taking 0/1 argument can be called as an operator  foo doSomething “x” is the same as foo.doSomething(“x”)  foo + 23 is the same as foo.+(23)  You can define both binary and unary operators  Only +, -, ~ and ! can be used as unary operators  As with binary operators, it’s just a method and  -foo is the same as foo.unary_-
  • 5. What About Precedence?  Scala looks at the first character of the operator name  All other special chars  */%  +-  :  =!  <>  &  ^  |  All letters  All assignment operators
  • 6. Operator Naming  Typically, you would use arithmetic operator symbols, but you don’t have to  Since operators are just methods, you can use non- standard characters  Δ,λ, γ, Ω, etc.  Neat/useful, but use sparingly, unless it makes your code easier to read and/or maintain  If the last character in an operator name is a colon, that method associates to the right
  • 7. Complex.scala package com.joeygibson.oopres class Complex(val real: Int, val imaginary: Int) { def +(operand: Complex): Complex = { new Complex(real + operand.real, imaginary + operand.imaginary) } def *(operand: Complex): Complex = { new Complex(real * operand.real - imaginary * operand.imaginary, real * operand.imaginary + imaginary * operand.real) } override def toString() = { real + (if (imaginary < 0) "" else "+") + imaginary + "i" } }
  • 8. ComplexTest.scala package com.joeygibson.oopres import org.junit.runner.RunWith import org.scalatest.FlatSpec import org.scalatest.matchers.ShouldMatchers import org.scalatest.junit.JUnitRunner @RunWith(classOf[JUnitRunner]) class ComplexTest extends FlatSpec with ShouldMatchers { "A Complex" should "sum up to 4-9i" in { val c1 = new Complex(1, 2) val c2 = new Complex(2, -3) val c3 = c1 + c2 val res = c1 + c2 * c3 res.toString should equal ("4-9i") } }
  • 9. Interesting Naming Examples package com.joeygibson.oopres import org.apache.commons.lang.StringUtils class Fragment(val text: String) { override def toString = text def Δ(other: Fragment): Fragment = { val diff = StringUtils.difference(text, other.text) new Fragment(diff) } def ::(other: Fragment): Fragment = { new Fragment(text + " || " + other.text) } }
  • 10. Testing Interesting Names package com.joeygibson.oopres @RunWith(classOf[JUnitRunner]) class FragmentTest extends FlatSpec with ShouldMatchers { it should "return proper differences" in { val f0 = new Fragment("Scala is groovy") val f1 = new Fragment("Scala is cool") val diff = f0 Δ f1 diff.toString should equal("cool") } it should "concatenate properly" in { val f0 = new Fragment("First Fragment") val f1 = new Fragment("Second Fragment") val f2 = f0 :: f1 f2.toString should equal ("Second Fragment || First Fragment") } }
  • 11. You Can Even Get Silly… package com.joeygibson.oopres class Absurdity(val text: String) { def //(other: Absurdity) = { new Absurdity(text + ", " + other.text) } def //(other: Absurdity) = { new Absurdity(other.text + ", " + text) } override def toString = text }
  • 12. Testing the Silliness package com.joeygibson.oopres @RunWith(classOf[JUnitRunner]) class AbsurdityTest extends FlatSpec with ShouldMatchers { it should "do something absurd" in { val a = new Absurdity("foo") val b = new Absurdity("bar") val c = a // b c.toString should equal ("foo, bar") } it should "do something equally absurd" in { val a = new Absurdity("foo") val b = new Absurdity("bar") val c = a // b c.toString should equal ("bar, foo") } }
  • 13. Arguments of Different Types  Define multiple versions of method, taking different types  Use Implicit conversions
  • 14. Multiple Defs of Operator package com.joeygibson.oopres class Complex2(val real: Int, val imaginary: Int) { def +(operand: Complex2): Complex2 = { new Complex2(real + operand.real, imaginary + operand.imaginary) } def +(operand: Int): Complex2 = this + new Complex2(operand, 0) def *(operand: Complex2): Complex2 = { new Complex2(real * operand.real - imaginary * operand.imaginary, real * operand.imaginary + imaginary * operand.real) } def *(operand: Int): Complex2 = this * new Complex2(operand, 1) def unary_- = new Complex2(-real, imaginary) override def toString() = { real + (if (imaginary < 0) "" else "+") + imaginary + "i" } }
  • 15. Testing Multiple Defs package com.joeygibson.oopres @RunWith(classOf[JUnitRunner]) class Complex2Test extends FlatSpec with ShouldMatchers { it should "convert int to Complex2" in { val c = new Complex2(1, 2) val d = c + 23 d.toString should equal ("24+2i") } // it should "convert int to Complex2, reversed" in { // val c = new Complex2(1, 2) // val d: Complex2 = 23 + c // // d.toString should equal ("24+2i") // } }
  • 16. Implicit Conversions  The implicit function must be in scope  It can live in the companion object of either class under consideration  Be careful with implicits, especially when using common types
  • 17. Implicit Conversions package com.joeygibson.oopres object Complex3 { implicit def intToComplex3(anInt: Int): Complex3 = new Complex3(anInt, 0) } class Complex3(val real: Int, val imaginary: Int) { def +(operand: Complex3): Complex3 = { new Complex3(real + operand.real, imaginary + operand.imaginary) } def *(operand: Complex3): Complex3 = { new Complex3(real * operand.real - imaginary * operand.imaginary, real * operand.imaginary + imaginary * operand.real) } def unary_- = new Complex3(-real, imaginary) override def toString() = { real + (if (imaginary < 0) "" else "+") + imaginary + "i" } }
  • 18. Testing Implicits package com.joeygibson.oopres @RunWith(classOf[JUnitRunner]) class Complex3Test extends FlatSpec with ShouldMatchers { it should "convert int to Complex3" in { val c = new Complex3(1, 2) val d = c + 23 d.toString should equal ("24+2i") } it should "convert int to Complex3, reversed" in { import com.joeygibson.oopres.Complex3.intToComplex3 val c = new Complex3(1, 2) val d: Complex3 = 23 + c d.toString should equal ("24+2i") } }
  • 19. Using Both package com.joeygibson.oopres object Complex4 { implicit def intToComplex4(anInt: Int): Complex4 = { printf("Implicitly converting to Complex4n") new Complex4(anInt, 0) } } class Complex4(val real: Int, val imaginary: Int) { def +(operand: Complex4): Complex4 = { new Complex4(real + operand.real, imaginary + operand.imaginary) } def +(operand: Int): Complex4 = this + new Complex4(operand, 0) def *(operand: Complex4): Complex4 = { new Complex4(real * operand.real - imaginary * operand.imaginary, real * operand.imaginary + imaginary * operand.real) } def *(operand: Int): Complex4 = this * new Complex4(operand, 0) def unary_- = new Complex4(-real, imaginary) override def toString() = { real + (if (imaginary < 0) "" else "+") + imaginary + "i" } }
  • 20. You Can’t Use ++ as Prefix package com.joeygibson.oopres class MyNumber(private var num: Int) { def number: Int = num override def toString = num.toString def ++ = { val n = num num += 1 new MyNumber(n) } def unary_++ = { num += 1 this } }
  • 21. The First One Works, The Second… package com.joeygibson.oopres @RunWith(classOf[JUnitRunner]) class MyNumberTest extends FlatSpec with ShouldMatchers { it should "post increment" in { val x = new MyNumber(23) val z = x++ z.number should equal (23) x.number should equal (24) } // it should "pre increment" in { // val x = new MyNumber(23) // val z = ++x // // z.number should equal (24) // x.number should equal (24) // } }
  • 22. ἐγώ ἐιμι  Email: joey@joeygibson.com  Blog: http://joeygibson.com  Original post: http://bit.ly/wNvAl  Twitter: @joeygibson  Facebook: http://facebook.com/joeygibson