Object

scalatutorial.sections

ObjectOrientedProgramming

Related Doc: package sections

Permalink

object ObjectOrientedProgramming extends FlatSpec with ScalaTutorialSection

Linear Supertypes
ScalaTutorialSection, Section, Matchers, Explicitly, MatcherWords, Tolerance, FlatSpec, FlatSpecLike, Documenting, Alerting, Notifying, Informing, CanVerb, MustVerb, ShouldVerb, TestRegistration, TestSuite, Suite, Serializable, Serializable, Assertions, TripleEquals, TripleEqualsSupport, AnyRef, Any
Ordering
  1. Alphabetic
  2. By Inheritance
Inherited
  1. ObjectOrientedProgramming
  2. ScalaTutorialSection
  3. Section
  4. Matchers
  5. Explicitly
  6. MatcherWords
  7. Tolerance
  8. FlatSpec
  9. FlatSpecLike
  10. Documenting
  11. Alerting
  12. Notifying
  13. Informing
  14. CanVerb
  15. MustVerb
  16. ShouldVerb
  17. TestRegistration
  18. TestSuite
  19. Suite
  20. Serializable
  21. Serializable
  22. Assertions
  23. TripleEquals
  24. TripleEqualsSupport
  25. AnyRef
  26. Any
  1. Hide All
  2. Show All
Visibility
  1. Public
  2. All

Type Members

  1. final class AWord extends AnyRef

    Permalink
    Definition Classes
    Matchers
  2. final class AnWord extends AnyRef

    Permalink
    Definition Classes
    Matchers
  3. sealed class AnyShouldWrapper[T] extends AnyRef

    Permalink
    Definition Classes
    Matchers
  4. class AssertionsHelper extends AnyRef

    Permalink
    Definition Classes
    Assertions
  5. final class BehaviorWord extends AnyRef

    Permalink
    Attributes
    protected
    Definition Classes
    FlatSpecLike
  6. class CheckingEqualizer[L] extends AnyRef

    Permalink
    Definition Classes
    TripleEqualsSupport
  7. class DecidedByEquality[A] extends Equality[A]

    Permalink
    Definition Classes
    Explicitly
  8. class DecidedWord extends AnyRef

    Permalink
    Definition Classes
    Explicitly
  9. class DeterminedByEquivalence[T] extends Equivalence[T]

    Permalink
    Definition Classes
    Explicitly
  10. class DeterminedWord extends AnyRef

    Permalink
    Definition Classes
    Explicitly
  11. class Equalizer[L] extends AnyRef

    Permalink
    Definition Classes
    TripleEqualsSupport
  12. final class HavePropertyMatcherGenerator extends AnyRef

    Permalink
    Definition Classes
    Matchers
  13. final class IgnoreVerbString extends AnyRef

    Permalink
    Attributes
    protected
    Definition Classes
    FlatSpecLike
  14. final class IgnoreVerbStringTaggedAs extends AnyRef

    Permalink
    Attributes
    protected
    Definition Classes
    FlatSpecLike
  15. final class IgnoreWord extends AnyRef

    Permalink
    Attributes
    protected
    Definition Classes
    FlatSpecLike
  16. final class InAndIgnoreMethods extends AnyRef

    Permalink
    Attributes
    protected
    Definition Classes
    FlatSpecLike
  17. final class InAndIgnoreMethodsAfterTaggedAs extends AnyRef

    Permalink
    Attributes
    protected
    Definition Classes
    FlatSpecLike
  18. final class ItVerbString extends AnyRef

    Permalink
    Attributes
    protected
    Definition Classes
    FlatSpecLike
  19. final class ItVerbStringTaggedAs extends AnyRef

    Permalink
    Attributes
    protected
    Definition Classes
    FlatSpecLike
  20. final class ItWord extends AnyRef

    Permalink
    Attributes
    protected
    Definition Classes
    FlatSpecLike
  21. final class KeyWord extends AnyRef

    Permalink
    Definition Classes
    Matchers
  22. trait NoArgTest extends () ⇒ Outcome with TestData

    Permalink
    Attributes
    protected
    Definition Classes
    TestSuite
  23. final class PlusOrMinusWrapper[T] extends AnyRef

    Permalink
    Definition Classes
    Tolerance
  24. final class RegexWord extends AnyRef

    Permalink
    Definition Classes
    Matchers
  25. final class RegexWrapper extends AnyRef

    Permalink
    Definition Classes
    Matchers
  26. class ResultOfBeWordForAny[T] extends AnyRef

    Permalink
    Definition Classes
    Matchers
  27. sealed class ResultOfBeWordForCollectedAny[T] extends AnyRef

    Permalink
    Definition Classes
    Matchers
  28. final class ResultOfBeWordForCollectedArray[T] extends ResultOfBeWordForCollectedAny[Array[T]]

    Permalink
    Definition Classes
    Matchers
  29. final class ResultOfCollectedAny[T] extends AnyRef

    Permalink
    Definition Classes
    Matchers
  30. final class ResultOfContainWordForCollectedAny[T] extends AnyRef

    Permalink
    Definition Classes
    Matchers
  31. final class ResultOfEndWithWordForCollectedString extends AnyRef

    Permalink
    Definition Classes
    Matchers
  32. final class ResultOfEndWithWordForString extends AnyRef

    Permalink
    Definition Classes
    Matchers
  33. final class ResultOfFullyMatchWordForCollectedString extends AnyRef

    Permalink
    Definition Classes
    Matchers
  34. final class ResultOfFullyMatchWordForString extends AnyRef

    Permalink
    Definition Classes
    Matchers
  35. final class ResultOfHaveWordForCollectedExtent[A] extends AnyRef

    Permalink
    Definition Classes
    Matchers
  36. final class ResultOfHaveWordForExtent[A] extends AnyRef

    Permalink
    Definition Classes
    Matchers
  37. final class ResultOfIncludeWordForCollectedString extends AnyRef

    Permalink
    Definition Classes
    Matchers
  38. final class ResultOfIncludeWordForString extends AnyRef

    Permalink
    Definition Classes
    Matchers
  39. final class ResultOfNotWordForCollectedAny[T] extends AnyRef

    Permalink
    Definition Classes
    Matchers
  40. final class ResultOfStartWithWordForCollectedString extends AnyRef

    Permalink
    Definition Classes
    Matchers
  41. final class ResultOfStartWithWordForString extends AnyRef

    Permalink
    Definition Classes
    Matchers
  42. trait StringCanWrapperForVerb extends AnyRef

    Permalink
    Definition Classes
    CanVerb
  43. trait StringMustWrapperForVerb extends AnyRef

    Permalink
    Definition Classes
    MustVerb
  44. final class StringShouldWrapper extends AnyShouldWrapper[String] with org.scalatest.Matchers.StringShouldWrapperForVerb

    Permalink
    Definition Classes
    Matchers
  45. trait StringShouldWrapperForVerb extends AnyRef

    Permalink
    Definition Classes
    ShouldVerb
  46. class TheAfterWord extends AnyRef

    Permalink
    Definition Classes
    Explicitly
  47. final class TheSameInstanceAsPhrase extends AnyRef

    Permalink
    Definition Classes
    Matchers
  48. final class TheyVerbString extends AnyRef

    Permalink
    Attributes
    protected
    Definition Classes
    FlatSpecLike
  49. final class TheyVerbStringTaggedAs extends AnyRef

    Permalink
    Attributes
    protected
    Definition Classes
    FlatSpecLike
  50. final class TheyWord extends AnyRef

    Permalink
    Attributes
    protected
    Definition Classes
    FlatSpecLike
  51. final class ValueWord extends AnyRef

    Permalink
    Definition Classes
    Matchers

Value Members

  1. final def !=(arg0: Any): Boolean

    Permalink
    Definition Classes
    AnyRef → Any
  2. def !==[T](right: Spread[T]): TripleEqualsInvocationOnSpread[T]

    Permalink
    Definition Classes
    TripleEqualsSupport
  3. def !==(right: Null): TripleEqualsInvocation[Null]

    Permalink
    Definition Classes
    TripleEqualsSupport
  4. def !==[T](right: T): TripleEqualsInvocation[T]

    Permalink
    Definition Classes
    TripleEqualsSupport
  5. final def ##(): Int

    Permalink
    Definition Classes
    AnyRef → Any
  6. def <[T](right: T)(implicit arg0: Ordering[T]): ResultOfLessThanComparison[T]

    Permalink
    Definition Classes
    Matchers
  7. def <=[T](right: T)(implicit arg0: Ordering[T]): ResultOfLessThanOrEqualToComparison[T]

    Permalink
    Definition Classes
    Matchers
  8. final def ==(arg0: Any): Boolean

    Permalink
    Definition Classes
    AnyRef → Any
  9. def ===[T](right: Spread[T]): TripleEqualsInvocationOnSpread[T]

    Permalink
    Definition Classes
    TripleEqualsSupport
  10. def ===(right: Null): TripleEqualsInvocation[Null]

    Permalink
    Definition Classes
    TripleEqualsSupport
  11. def ===[T](right: T): TripleEqualsInvocation[T]

    Permalink
    Definition Classes
    TripleEqualsSupport
  12. def >[T](right: T)(implicit arg0: Ordering[T]): ResultOfGreaterThanComparison[T]

    Permalink
    Definition Classes
    Matchers
  13. def >=[T](right: T)(implicit arg0: Ordering[T]): ResultOfGreaterThanOrEqualToComparison[T]

    Permalink
    Definition Classes
    Matchers
  14. def a[T](implicit arg0: ClassTag[T]): ResultOfATypeInvocation[T]

    Permalink
    Definition Classes
    Matchers
  15. val a: AWord

    Permalink
    Definition Classes
    Matchers
  16. val after: TheAfterWord

    Permalink
    Definition Classes
    Explicitly
  17. def alert: Alerter

    Permalink
    Attributes
    protected
    Definition Classes
    FlatSpecLike → Alerting
  18. def all(xs: String)(implicit collecting: Collecting[Char, String], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[Char]

    Permalink
    Definition Classes
    Matchers
  19. def all[K, V, JMAP[k, v] <: Map[k, v]](xs: JMAP[K, V])(implicit collecting: Collecting[Entry[K, V], JMAP[K, V]], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[Entry[K, V]]

    Permalink
    Definition Classes
    Matchers
  20. def all[E, C[_]](xs: C[E])(implicit collecting: Collecting[E, C[E]], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[E]

    Permalink
    Definition Classes
    Matchers
  21. def allElementsOf[R](elements: GenTraversable[R]): ResultOfAllElementsOfApplication

    Permalink
    Definition Classes
    Matchers
  22. def allOf(firstEle: Any, secondEle: Any, remainingEles: Any*)(implicit pos: Position): ResultOfAllOfApplication

    Permalink
    Definition Classes
    Matchers
  23. def an[T](implicit arg0: ClassTag[T]): ResultOfAnTypeInvocation[T]

    Permalink
    Definition Classes
    Matchers
  24. val an: AnWord

    Permalink
    Definition Classes
    Matchers
  25. final def asInstanceOf[T0]: T0

    Permalink
    Definition Classes
    Any
  26. macro def assert(condition: Boolean, clue: Any)(implicit prettifier: Prettifier, pos: Position): Assertion

    Permalink
    Definition Classes
    Assertions
  27. macro def assert(condition: Boolean)(implicit prettifier: Prettifier, pos: Position): Assertion

    Permalink
    Definition Classes
    Assertions
  28. macro def assertCompiles(code: String)(implicit pos: Position): Assertion

    Permalink
    Definition Classes
    Assertions
  29. macro def assertDoesNotCompile(code: String)(implicit pos: Position): Assertion

    Permalink
    Definition Classes
    Assertions
  30. def assertResult(expected: Any)(actual: Any)(implicit prettifier: Prettifier, pos: Position): Assertion

    Permalink
    Definition Classes
    Assertions
  31. def assertResult(expected: Any, clue: Any)(actual: Any)(implicit prettifier: Prettifier, pos: Position): Assertion

    Permalink
    Definition Classes
    Assertions
  32. def assertThrows[T <: AnyRef](f: ⇒ Any)(implicit classTag: ClassTag[T], pos: Position): Assertion

    Permalink
    Definition Classes
    Assertions
  33. macro def assertTypeError(code: String)(implicit pos: Position): Assertion

    Permalink
    Definition Classes
    Assertions
  34. val assertionsHelper: AssertionsHelper

    Permalink
    Definition Classes
    Assertions
  35. macro def assume(condition: Boolean, clue: Any)(implicit prettifier: Prettifier, pos: Position): Assertion

    Permalink
    Definition Classes
    Assertions
  36. macro def assume(condition: Boolean)(implicit prettifier: Prettifier, pos: Position): Assertion

    Permalink
    Definition Classes
    Assertions
  37. def atLeast(num: Int, xs: String)(implicit collecting: Collecting[Char, String], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[Char]

    Permalink
    Definition Classes
    Matchers
  38. def atLeast[K, V, JMAP[k, v] <: Map[k, v]](num: Int, xs: JMAP[K, V])(implicit collecting: Collecting[Entry[K, V], JMAP[K, V]], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[Entry[K, V]]

    Permalink
    Definition Classes
    Matchers
  39. def atLeast[E, C[_]](num: Int, xs: C[E])(implicit collecting: Collecting[E, C[E]], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[E]

    Permalink
    Definition Classes
    Matchers
  40. def atLeastOneElementOf(elements: GenTraversable[Any]): ResultOfAtLeastOneElementOfApplication

    Permalink
    Definition Classes
    Matchers
  41. def atLeastOneOf(firstEle: Any, secondEle: Any, remainingEles: Any*)(implicit pos: Position): ResultOfAtLeastOneOfApplication

    Permalink
    Definition Classes
    Matchers
  42. def atMost(num: Int, xs: String)(implicit collecting: Collecting[Char, String], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[Char]

    Permalink
    Definition Classes
    Matchers
  43. def atMost[K, V, JMAP[k, v] <: Map[k, v]](num: Int, xs: JMAP[K, V])(implicit collecting: Collecting[Entry[K, V], JMAP[K, V]], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[Entry[K, V]]

    Permalink
    Definition Classes
    Matchers
  44. def atMost[E, C[_]](num: Int, xs: C[E])(implicit collecting: Collecting[E, C[E]], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[E]

    Permalink
    Definition Classes
    Matchers
  45. def atMostOneElementOf[R](elements: GenTraversable[R]): ResultOfAtMostOneElementOfApplication

    Permalink
    Definition Classes
    Matchers
  46. def atMostOneOf(firstEle: Any, secondEle: Any, remainingEles: Any*)(implicit pos: Position): ResultOfAtMostOneOfApplication

    Permalink
    Definition Classes
    Matchers
  47. val be: BeWord

    Permalink
    Definition Classes
    MatcherWords
  48. val behave: BehaveWord

    Permalink
    Attributes
    protected
    Definition Classes
    FlatSpecLike
  49. val behavior: BehaviorWord

    Permalink
    Attributes
    protected
    Definition Classes
    FlatSpecLike
  50. def between(from: Int, upTo: Int, xs: String)(implicit collecting: Collecting[Char, String], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[Char]

    Permalink
    Definition Classes
    Matchers
  51. def between[K, V, JMAP[k, v] <: Map[k, v]](from: Int, upTo: Int, xs: JMAP[K, V])(implicit collecting: Collecting[Entry[K, V], JMAP[K, V]], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[Entry[K, V]]

    Permalink
    Definition Classes
    Matchers
  52. def between[E, C[_]](from: Int, upTo: Int, xs: C[E])(implicit collecting: Collecting[E, C[E]], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[E]

    Permalink
    Definition Classes
    Matchers
  53. def cancel(cause: Throwable)(implicit pos: Position): Nothing

    Permalink
    Definition Classes
    Assertions
  54. def cancel(message: String, cause: Throwable)(implicit pos: Position): Nothing

    Permalink
    Definition Classes
    Assertions
  55. def cancel(message: String)(implicit pos: Position): Nothing

    Permalink
    Definition Classes
    Assertions
  56. def cancel()(implicit pos: Position): Nothing

    Permalink
    Definition Classes
    Assertions
  57. def clone(): AnyRef

    Permalink
    Attributes
    protected[java.lang]
    Definition Classes
    AnyRef
    Annotations
    @throws( ... )
  58. val compile: CompileWord

    Permalink
    Definition Classes
    MatcherWords
  59. val contain: ContainWord

    Permalink
    Definition Classes
    MatcherWords
  60. def conversionCheckedConstraint[A, B](implicit equivalenceOfA: Equivalence[A], cnv: (B) ⇒ A): CanEqual[A, B]

    Permalink
    Definition Classes
    TripleEquals → TripleEqualsSupport
  61. def convertEquivalenceToAToBConstraint[A, B](equivalenceOfB: Equivalence[B])(implicit ev: <:<[A, B]): CanEqual[A, B]

    Permalink
    Definition Classes
    TripleEquals → TripleEqualsSupport
  62. def convertEquivalenceToAToBConversionConstraint[A, B](equivalenceOfB: Equivalence[B])(implicit ev: (A) ⇒ B): CanEqual[A, B]

    Permalink
    Definition Classes
    TripleEquals → TripleEqualsSupport
  63. def convertEquivalenceToBToAConstraint[A, B](equivalenceOfA: Equivalence[A])(implicit ev: <:<[B, A]): CanEqual[A, B]

    Permalink
    Definition Classes
    TripleEquals → TripleEqualsSupport
  64. def convertEquivalenceToBToAConversionConstraint[A, B](equivalenceOfA: Equivalence[A])(implicit ev: (B) ⇒ A): CanEqual[A, B]

    Permalink
    Definition Classes
    TripleEquals → TripleEqualsSupport
  65. implicit def convertNumericToPlusOrMinusWrapper[T](pivot: T)(implicit arg0: Numeric[T]): PlusOrMinusWrapper[T]

    Permalink
    Definition Classes
    Tolerance
  66. implicit def convertSymbolToHavePropertyMatcherGenerator(symbol: Symbol)(implicit prettifier: Prettifier, pos: Position): HavePropertyMatcherGenerator

    Permalink
    Definition Classes
    Matchers
  67. implicit def convertToAnyShouldWrapper[T](o: T)(implicit pos: Position, prettifier: Prettifier): AnyShouldWrapper[T]

    Permalink
    Definition Classes
    Matchers
  68. def convertToCheckingEqualizer[T](left: T): CheckingEqualizer[T]

    Permalink
    Definition Classes
    TripleEquals → TripleEqualsSupport
  69. implicit def convertToEqualizer[T](left: T): Equalizer[T]

    Permalink
    Definition Classes
    TripleEquals → TripleEqualsSupport
  70. implicit def convertToInAndIgnoreMethods(resultOfStringPassedToVerb: ResultOfStringPassedToVerb): InAndIgnoreMethods

    Permalink
    Attributes
    protected
    Definition Classes
    FlatSpecLike
  71. implicit def convertToInAndIgnoreMethodsAfterTaggedAs(resultOfTaggedAsInvocation: ResultOfTaggedAsInvocation): InAndIgnoreMethodsAfterTaggedAs

    Permalink
    Attributes
    protected
    Definition Classes
    FlatSpecLike
  72. implicit def convertToRegexWrapper(o: Regex): RegexWrapper

    Permalink
    Definition Classes
    Matchers
  73. implicit def convertToStringCanWrapper(o: String)(implicit position: Position): StringCanWrapperForVerb

    Permalink
    Definition Classes
    CanVerb
  74. implicit def convertToStringMustWrapperForVerb(o: String)(implicit position: Position): StringMustWrapperForVerb

    Permalink
    Definition Classes
    MustVerb
  75. implicit def convertToStringShouldWrapper(o: String)(implicit pos: Position, prettifier: Prettifier): StringShouldWrapper

    Permalink
    Definition Classes
    Matchers
  76. implicit def convertToStringShouldWrapperForVerb(o: String)(implicit position: Position): StringShouldWrapperForVerb

    Permalink
    Definition Classes
    ShouldVerb
  77. val decided: DecidedWord

    Permalink
    Definition Classes
    Explicitly
  78. def defaultEquality[A]: Equality[A]

    Permalink
    Definition Classes
    TripleEqualsSupport
  79. val defined: DefinedWord

    Permalink
    Definition Classes
    MatcherWords
  80. def definedAt[T](right: T): ResultOfDefinedAt[T]

    Permalink
    Definition Classes
    Matchers
  81. val determined: DeterminedWord

    Permalink
    Definition Classes
    Explicitly
  82. def dynamicBinding(res0: Boolean, res1: Boolean): Unit

    Permalink

    Let’s see how functions create and encapsulate data structures.

    Functions and Data

    Let’s see how functions create and encapsulate data structures.

    We want to design a package for doing rational arithmetic.

    A rational number x / y is represented by two integers:

    • its numerator x, and
    • its denominator y.

    Rational Addition

    Suppose we want to implement the addition of two rational numbers.

    def addRationalNumerator(n1: Int, d1: Int, n2: Int, d2: Int): Int
    def addRationalDenominator(n1: Int, d1: Int, n2: Int, d2: Int): Int

    It would be difficult to manage all these numerators and denominators!

    A better choice is to combine the numerator and denominator of a rational number in a data structure.

    Classes

    In Scala, we do this by defining a class:

    class Rational(x: Int, y: Int) {
      def numer = x
      def denom = y
    }

    This definition introduces two entities:

    • A new type, named Rational.
    • A constructor Rational to create elements of this type.

    Scala keeps the names of types and values in different namespaces. So there's no conflict between the two definitions of Rational.

    Objects

    We call the elements of a class type objects.

    We create an object by prefixing an application of the constructor of the class with the operator new.

    new Rational(1, 2)

    Members of an Object

    Objects of the class Rational have two members, numer and denom.

    We select the members of an object with the infix operator . (like in Java).

    val x = new Rational(1, 2) // x: Rational = Rational@2abe0e27
    x.numer // 1
    x.denom // 2

    Rational Arithmetic

    We can now define the arithmetic functions that implement the standard rules.

    n1 / d1 + n2 / d2 = (n1 * d2 + n2 * d1) / (d1 * d2)
    n1 / d1 - n2 / d2 = (n1 * d2 - n2 * d1) / (d1 * d2)
    n1 / d1 * n2 / d2 = (n1 * n2) / (d1 * d2)
    n1 / d1 / n2 / d2 = (n1 * d2) / (d1 * n2)
    n1 / d1 = n2 / d2 iff n1 * d2 = d1 * n2

    Implementing Rational Arithmetic

    def addRational(r: Rational, s: Rational): Rational =
      new Rational(
        r.numer * s.denom + s.numer * r.denom,
        r.denom * s.denom
      )
    
    def makeString(r: Rational) =
      r.numer + "/" + r.denom

    And then:

    makeString(addRational(new Rational(1, 2), new Rational(2, 3)))

    Methods

    One can go further and also package functions operating on a data abstraction in the data abstraction itself.

    Such functions are called methods.

    Rational numbers now would have, in addition to the functions numer and denom, the functions add, sub, mul, div, equal, toString.

    Here's a possible implementation:

    class Rational(x: Int, y: Int) {
      def numer = x
      def denom = y
      def add(r: Rational) =
        new Rational(numer * r.denom + r.numer * denom, denom * r.denom)
      def mul(r: Rational) = ...
      ...
      override def toString = numer + "/" + denom
    }

    Note that the modifier override declares that toString redefines a method that already exists (in the class java.lang.Object).

    Here is how one might use the new Rational abstraction:

    val x = new Rational(1, 3)
    val y = new Rational(5, 7)
    val z = new Rational(3, 2)
    x.add(y).mul(z)

    Data Abstraction

    In the above example rational numbers weren't always represented in their simplest form.

    One would expect the rational numbers to be simplified:

    • reduce them to their smallest numerator and denominator by dividing both with a divisor.

    We could implement this in each rational operation, but it would be easy to forget this division in an operation.

    A better alternative consists of simplifying the representation in the class when the objects are constructed:

    class Rational(x: Int, y: Int) {
      private def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
      private val g = gcd(x, y)
      def numer = x / g
      def denom = y / g
      ...
    }

    gcd and g are private members; we can only access them from inside the Rational class.

    In this example, we calculate gcd immediately, so that its value can be re-used in the calculations of numer and denom.

    It is also possible to call gcd in the code of numer and denom:

    class Rational(x: Int, y: Int) {
      private def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
      def numer = x / gcd(x, y)
      def denom = y / gcd(x, y)
    }

    This can be advantageous if it is expected that the functions numer and denom are called infrequently.

    It is equally possible to turn numer and denom into vals, so that they are computed only once:

    class Rational(x: Int, y: Int) {
      private def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
      val numer = x / gcd(x, y)
      val denom = y / gcd(x, y)
    }

    This can be advantageous if the functions numer and denom are called often.

    The Client's View

    Clients observe exactly the same behavior in each case.

    This ability to choose different implementations of the data without affecting clients is called data abstraction.

    It is a cornerstone of software engineering.

    Self Reference

    On the inside of a class, the name this represents the object on which the current method is executed.

    Add the functions less and max to the class Rational.

    class Rational(x: Int, y: Int) {
      ...
      def less(that: Rational) =
      numer * that.denom < that.numer * denom
    
      def max(that: Rational) =
        if (this.less(that)) that else this
    }

    Note that a simple name x, which refers to another member of the class, is an abbreviation of this.x. Thus, an equivalent way to formulate less is as follows.

    def less(that: Rational) =
      this.numer * that.denom < that.numer * this.denom

    Preconditions

    Let's say our Rational class requires that the denominator is positive.

    We can enforce this by calling the require function.

    class Rational(x: Int, y: Int) {
      require(y > 0, "denominator must be positive")
      ...
    }

    require is a predefined function. It takes a condition and an optional message string. If the condition passed to require is false, an IllegalArgumentException is thrown with the given message string.

    Assertions

    Besides require, there is also assert.

    Assert also takes a condition and an optional message string as parameters. E.g.

    val x = sqrt(y)
    assert(x >= 0)

    Like require, a failing assert will also throw an exception, but it's a different one: AssertionError for assert, IllegalArgumentException for require.

    This reflects a difference in intent

    • require is used to enforce a precondition on the caller of a function.
    • assert is used as to check the code of the function itself.

    Constructors

    In Scala, a class implicitly introduces a constructor. This one is called the primary constructor of the class.

    The primary constructor:

    • takes the parameters of the class
    • and executes all statements in the class body (such as the require a couple of slides back).

    Auxiliary Constructors

    Scala also allows the declaration of auxiliary constructors.

    These are methods named this.

    Adding an auxiliary constructor to the class Rational:

    class Rational(x: Int, y: Int) {
      def this(x: Int) = this(x, 1)
      ...
    }

    Classes and Substitutions

    We previously defined the meaning of a function application using a computation model based on substitution. Now we extend this model to classes and objects.

    How is an instantiation of the class new C(e1, …, en) evaluated?

    The expression arguments e1, …, en are evaluated like the arguments of a normal function. That's it.

    The resulting expression, say, new C(v1, …, vn), is already a value.

    Now suppose that we have a class definition,

    class C(x1, …, xn) {
      …
      def f(y1, …, ym) = b
      …
    }

    where:

    • The formal parameters of the class are x1, …, xn.
    • The class defines a method f with formal parameters y1, …, ym.

    (The list of function parameters can be absent. For simplicity, we have omitted the parameter types.)

    How is the following expression evaluated?

    new C(v1, …, vn).f(w1, …, wm)

    The following three substitutions happen:

    • the substitution of the formal parameters y1, …, ym of the function f by the arguments w1, …, wm,
    • the substitution of the formal parameters x1, …, xn of the class C by the class arguments v1, …, vn,
    • the substitution of the self reference this by the value of the object new C(v1, …, vn).

    Operators

    In principle, the rational numbers defined by Rational are as natural as integers.

    But for the user of these abstractions, there is a noticeable difference:

    • We write x + y, if x and y are integers, but
    • We write r.add(s) if r and s are rational numbers.

    In Scala, we can eliminate this difference because operators can be used as identifiers.

    Thus, an identifier can be:

    • Alphanumeric: starting with a letter, followed by a sequence of letters or numbers
    • Symbolic: starting with an operator symbol, followed by other operator symbols.
    • The underscore character '_' counts as a letter.
    • Alphanumeric identifiers can also end in an underscore, followed by some operator symbols.

    Examples of identifiers:

    x1     *     +?%&     vector_++     counter_=

    Operators for Rationals

    So, here is a more natural definition of class Rational:

    class Rational(x: Int, y: Int) {
      private def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
      private val g = gcd(x, y)
      def numer = x / g
      def denom = y / g
      def + (r: Rational) =
        new Rational(
          numer * r.denom + r.numer * denom,
          denom * r.denom
        )
      def - (r: Rational) = ...
      def * (r: Rational) = ...
      ...
    }

    and then rational numbers can be used like Int or Double:

    val x = new Rational(1, 2)
    val y = new Rational(1, 3)
    x * x + y * y

    Precedence Rules

    The precedence of an operator is determined by its first character.

    The following table lists the characters in increasing order of priority precedence:

    (all letters)
    |
    ^
    &
    < >
    = !
    :
    + -
    * / %
    (all other special characters)

    Abstract Classes

    Consider the task of writing a class for sets of integers with the following operations.

    abstract class IntSet {
      def incl(x: Int): IntSet
      def contains(x: Int): Boolean
    }

    IntSet is an abstract class.

    Abstract classes can contain members which are missing an implementation (in our case, incl and contains).

    Consequently, no instances of an abstract class can be created with the operator new.

    Class Extensions

    Let's consider implementing sets as binary trees.

    There are two types of possible trees: a tree for the empty set, and a tree consisting of an integer and two sub-trees.

    Here are their implementations:

    class Empty extends IntSet {
      def contains(x: Int): Boolean = false
      def incl(x: Int): IntSet = new NonEmpty(x, new Empty, new Empty)
    }
    
    class NonEmpty(elem: Int, left: IntSet, right: IntSet) extends IntSet {
    
      def contains(x: Int): Boolean =
        if (x < elem) left contains x
        else if (x > elem) right contains x
        else true
    
      def incl(x: Int): IntSet =
        if (x < elem) new NonEmpty(elem, left incl x, right)
        else if (x > elem) new NonEmpty(elem, left, right incl x)
        else this
    }

    Empty and NonEmpty both extend the class IntSet.

    This implies that the types Empty and NonEmpty conform to the type IntSet

    • an object of type Empty or NonEmpty can be used wherever an object of type IntSet is required.

    IntSet is called the superclass of Empty and NonEmpty.

    Empty and NonEmpty are subclasses of IntSet.

    In Scala, any user-defined class extends another class.

    If no superclass is given, the standard class Object in the Java package java.lang is assumed.

    The direct or indirect superclasses of a class C are called base classes of C.

    So, the base classes of NonEmpty are IntSet and Object.

    Implementation and Overriding

    The definitions of contains and incl in the classes Empty and NonEmpty implement the abstract functions in the base trait IntSet.

    It is also possible to redefine an existing, non-abstract definition in a subclass by using override.

    abstract class Base {
      def foo = 1
      def bar: Int
    }
    
    class Sub extends Base {
      override def foo = 2
      def bar = 3
    }

    Object Definitions

    In the IntSet example, one could argue that there is really only a single empty IntSet.

    So it seems overkill to have the user create many instances of it.

    We can express this case better with an object definition:

    object Empty extends IntSet {
      def contains(x: Int): Boolean = false
      def incl(x: Int): IntSet = new NonEmpty(x, Empty, Empty)
    }

    This defines a singleton object named Empty.

    No other Empty instances can be (or need to be) created.

    Singleton objects are values, so Empty evaluates to itself.

    Dynamic Binding

    Object-oriented languages (including Scala) implement dynamic method dispatch.

    This means that the code invoked by a method call depends on the runtime type of the object that contains the method.

  83. val empty: EmptyWord

    Permalink
    Definition Classes
    MatcherWords
  84. val endWith: EndWithWord

    Permalink
    Definition Classes
    MatcherWords
  85. final def eq(arg0: AnyRef): Boolean

    Permalink
    Definition Classes
    AnyRef
  86. def equal(o: Null): Matcher[AnyRef]

    Permalink
    Definition Classes
    Matchers
  87. def equal[T](spread: Spread[T]): Matcher[T]

    Permalink
    Definition Classes
    Matchers
  88. def equal(right: Any): MatcherFactory1[Any, Equality]

    Permalink
    Definition Classes
    MatcherWords
  89. def equals(arg0: Any): Boolean

    Permalink
    Definition Classes
    AnyRef → Any
  90. def every(xs: String)(implicit collecting: Collecting[Char, String], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[Char]

    Permalink
    Definition Classes
    Matchers
  91. def every[K, V, JMAP[k, v] <: Map[k, v]](xs: JMAP[K, V])(implicit collecting: Collecting[Entry[K, V], JMAP[K, V]], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[Entry[K, V]]

    Permalink
    Definition Classes
    Matchers
  92. def every[E, C[_]](xs: C[E])(implicit collecting: Collecting[E, C[E]], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[E]

    Permalink
    Definition Classes
    Matchers
  93. def exactly(num: Int, xs: String)(implicit collecting: Collecting[Char, String], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[Char]

    Permalink
    Definition Classes
    Matchers
  94. def exactly[K, V, JMAP[k, v] <: Map[k, v]](num: Int, xs: JMAP[K, V])(implicit collecting: Collecting[Entry[K, V], JMAP[K, V]], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[Entry[K, V]]

    Permalink
    Definition Classes
    Matchers
  95. def exactly[E, C[_]](num: Int, xs: C[E])(implicit collecting: Collecting[E, C[E]], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[E]

    Permalink
    Definition Classes
    Matchers
  96. final def execute(testName: String, configMap: ConfigMap, color: Boolean, durations: Boolean, shortstacks: Boolean, fullstacks: Boolean, stats: Boolean): Unit

    Permalink
    Definition Classes
    Suite
  97. val exist: ExistWord

    Permalink
    Definition Classes
    MatcherWords
  98. def expectedTestCount(filter: Filter): Int

    Permalink
    Definition Classes
    Suite
  99. def fail(cause: Throwable)(implicit pos: Position): Nothing

    Permalink
    Definition Classes
    Assertions
  100. def fail(message: String, cause: Throwable)(implicit pos: Position): Nothing

    Permalink
    Definition Classes
    Assertions
  101. def fail(message: String)(implicit pos: Position): Nothing

    Permalink
    Definition Classes
    Assertions
  102. def fail()(implicit pos: Position): Nothing

    Permalink
    Definition Classes
    Assertions
  103. def finalize(): Unit

    Permalink
    Attributes
    protected[java.lang]
    Definition Classes
    AnyRef
    Annotations
    @throws( classOf[java.lang.Throwable] )
  104. val fullyMatch: FullyMatchWord

    Permalink
    Definition Classes
    MatcherWords
  105. final def getClass(): Class[_]

    Permalink
    Definition Classes
    AnyRef → Any
  106. def hashCode(): Int

    Permalink
    Definition Classes
    AnyRef → Any
  107. val have: HaveWord

    Permalink
    Definition Classes
    MatcherWords
  108. val ignore: IgnoreWord

    Permalink
    Attributes
    protected
    Definition Classes
    FlatSpecLike
  109. def inOrder(firstEle: Any, secondEle: Any, remainingEles: Any*)(implicit pos: Position): ResultOfInOrderApplication

    Permalink
    Definition Classes
    Matchers
  110. def inOrderElementsOf[R](elements: GenTraversable[R]): ResultOfInOrderElementsOfApplication

    Permalink
    Definition Classes
    Matchers
  111. def inOrderOnly[T](firstEle: Any, secondEle: Any, remainingEles: Any*)(implicit pos: Position): ResultOfInOrderOnlyApplication

    Permalink
    Definition Classes
    Matchers
  112. val include: IncludeWord

    Permalink
    Definition Classes
    MatcherWords
  113. def info: Informer

    Permalink
    Attributes
    protected
    Definition Classes
    FlatSpecLike → Informing
  114. def intercept[T <: AnyRef](f: ⇒ Any)(implicit classTag: ClassTag[T], pos: Position): T

    Permalink
    Definition Classes
    Assertions
  115. final def isInstanceOf[T0]: Boolean

    Permalink
    Definition Classes
    Any
  116. val it: ItWord

    Permalink
    Attributes
    protected
    Definition Classes
    FlatSpecLike
  117. val key: KeyWord

    Permalink
    Definition Classes
    Matchers
  118. val length: LengthWord

    Permalink
    Definition Classes
    MatcherWords
  119. def lowPriorityConversionCheckedConstraint[A, B](implicit equivalenceOfB: Equivalence[B], cnv: (A) ⇒ B): CanEqual[A, B]

    Permalink
    Definition Classes
    TripleEquals → TripleEqualsSupport
  120. def lowPriorityTypeCheckedConstraint[A, B](implicit equivalenceOfB: Equivalence[B], ev: <:<[A, B]): CanEqual[A, B]

    Permalink
    Definition Classes
    TripleEquals → TripleEqualsSupport
  121. def markup: Documenter

    Permalink
    Attributes
    protected
    Definition Classes
    FlatSpecLike → Documenting
  122. val matchPattern: MatchPatternWord

    Permalink
    Definition Classes
    MatcherWords
  123. def message(expectedMessage: String): ResultOfMessageWordApplication

    Permalink
    Definition Classes
    Matchers
  124. final def ne(arg0: AnyRef): Boolean

    Permalink
    Definition Classes
    AnyRef
  125. def nestedSuites: IndexedSeq[Suite]

    Permalink
    Definition Classes
    Suite
  126. def no(xs: String)(implicit collecting: Collecting[Char, String], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[Char]

    Permalink
    Definition Classes
    Matchers
  127. def no[K, V, JMAP[k, v] <: Map[k, v]](xs: JMAP[K, V])(implicit collecting: Collecting[Entry[K, V], JMAP[K, V]], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[Entry[K, V]]

    Permalink
    Definition Classes
    Matchers
  128. def no[E, C[_]](xs: C[E])(implicit collecting: Collecting[E, C[E]], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[E]

    Permalink
    Definition Classes
    Matchers
  129. def noElementsOf(elements: GenTraversable[Any]): ResultOfNoElementsOfApplication

    Permalink
    Definition Classes
    Matchers
  130. def noException(implicit pos: Position): NoExceptionWord

    Permalink
    Definition Classes
    MatcherWords
  131. def noneOf(firstEle: Any, secondEle: Any, remainingEles: Any*)(implicit pos: Position): ResultOfNoneOfApplication

    Permalink
    Definition Classes
    Matchers
  132. val not: NotWord

    Permalink
    Definition Classes
    MatcherWords
  133. def note: Notifier

    Permalink
    Attributes
    protected
    Definition Classes
    FlatSpecLike → Notifying
  134. final def notify(): Unit

    Permalink
    Definition Classes
    AnyRef
  135. final def notifyAll(): Unit

    Permalink
    Definition Classes
    AnyRef
  136. def of[T](implicit ev: ClassTag[T]): ResultOfOfTypeInvocation[T]

    Permalink
    Definition Classes
    Matchers
  137. def oneElementOf(elements: GenTraversable[Any]): ResultOfOneElementOfApplication

    Permalink
    Definition Classes
    Matchers
  138. def oneOf(firstEle: Any, secondEle: Any, remainingEles: Any*)(implicit pos: Position): ResultOfOneOfApplication

    Permalink
    Definition Classes
    Matchers
  139. def only(xs: Any*)(implicit pos: Position): ResultOfOnlyApplication

    Permalink
    Definition Classes
    Matchers
  140. def pending: Assertion with PendingStatement

    Permalink
    Definition Classes
    Assertions
  141. def pendingUntilFixed(f: ⇒ Unit)(implicit pos: Position): Assertion with PendingStatement

    Permalink
    Definition Classes
    Assertions
  142. val readable: ReadableWord

    Permalink
    Definition Classes
    MatcherWords
  143. def reducer(res0: Int, res1: Int): Unit

    Permalink

    Dynamic dispatch of methods is analogous to calls to higher-order functions.

    Dynamic dispatch of methods is analogous to calls to higher-order functions.

    Can we implement one concept in terms of the other?

    • Objects in terms of higher-order functions?
    • Higher-order functions in terms of objects?

    Traits

    In Scala, a class can only have one superclass.

    But what if a class has several natural supertypes to which it conforms or from which it wants to inherit code?

    Here, you could use traits.

    A trait is declared like an abstract class, just with trait instead of abstract class.

    trait Planar {
      def height: Int
      def width: Int
      def surface = height * width
    }

    Classes, objects and traits can inherit from at most one class but arbitrary many traits:

    class Square extends Shape with Planar with Movable …

    On the other hand, traits cannot have (value) parameters, only classes can.

    Scala's Class Hierarchy

    Top Types

    At the top of the type hierarchy we find:

    • Any
      • The base type of all types
      • Methods: ==, !=, equals, hashCode, toString
    • AnyRef
      • The base type of all reference types
      • Alias of java.lang.Object
    • AnyVal
      • The base type of all primitive types

    Bottom Type

    Nothing is at the bottom of Scala's type hierarchy. It is a subtype of every other type.

    There is no value of type Nothing.

    Why is that useful?

    • To signal abnormal termination
    • As an element type of empty collections

    The Null Type

    Every reference class type also has null as a value.

    The type of null is Null.

    Null is a subtype of every class that inherits from Object; it is incompatible with subtypes of AnyVal.

    val x = null         // x: Null
    val y: String = null // y: String
    val z: Int = null    // error: type mismatch

    Exercise

    The following Reducer abstract class defines how to reduce a list of values into a single value by starting with an initial value and combining it with each element of the list:

  144. val regex: RegexWord

    Permalink
    Definition Classes
    Matchers
  145. final def registerIgnoredTest(testText: String, testTags: Tag*)(testFun: ⇒ Any)(implicit pos: Position): Unit

    Permalink
    Definition Classes
    FlatSpecLike → TestRegistration
  146. final def registerTest(testText: String, testTags: Tag*)(testFun: ⇒ Any)(implicit pos: Position): Unit

    Permalink
    Definition Classes
    FlatSpecLike → TestRegistration
  147. def rerunner: Option[String]

    Permalink
    Definition Classes
    Suite
  148. def run(testName: Option[String], args: Args): Status

    Permalink
    Definition Classes
    FlatSpecLike → Suite
  149. def runNestedSuites(args: Args): Status

    Permalink
    Attributes
    protected
    Definition Classes
    Suite
  150. def runTest(testName: String, args: Args): Status

    Permalink
    Attributes
    protected
    Definition Classes
    FlatSpecLike → TestSuite → Suite
  151. def runTests(testName: Option[String], args: Args): Status

    Permalink
    Attributes
    protected
    Definition Classes
    FlatSpecLike → Suite
  152. implicit val shorthandSharedTestRegistrationFunction: StringVerbBehaveLikeInvocation

    Permalink
    Attributes
    protected
    Definition Classes
    FlatSpecLike
  153. implicit val shorthandTestRegistrationFunction: StringVerbStringInvocation

    Permalink
    Attributes
    protected
    Definition Classes
    FlatSpecLike
  154. val size: SizeWord

    Permalink
    Definition Classes
    MatcherWords
  155. val sorted: SortedWord

    Permalink
    Definition Classes
    MatcherWords
  156. val startWith: StartWithWord

    Permalink
    Definition Classes
    MatcherWords
  157. final val styleName: String

    Permalink
    Definition Classes
    FlatSpecLike → Suite
  158. final val succeed: Assertion

    Permalink
    Definition Classes
    Assertions
  159. def suiteId: String

    Permalink
    Definition Classes
    Suite
  160. def suiteName: String

    Permalink
    Definition Classes
    Suite
  161. final def synchronized[T0](arg0: ⇒ T0): T0

    Permalink
    Definition Classes
    AnyRef
  162. def tags: Map[String, Set[String]]

    Permalink
    Definition Classes
    FlatSpecLike → Suite
  163. def testDataFor(testName: String, theConfigMap: ConfigMap): TestData

    Permalink
    Definition Classes
    FlatSpecLike → Suite
  164. def testNames: Set[String]

    Permalink
    Definition Classes
    FlatSpecLike → Suite
  165. def the[T](implicit arg0: ClassTag[T], pos: Position): ResultOfTheTypeInvocation[T]

    Permalink
    Definition Classes
    Matchers
  166. def theSameElementsAs(xs: GenTraversable[_]): ResultOfTheSameElementsAsApplication

    Permalink
    Definition Classes
    Matchers
  167. def theSameElementsInOrderAs(xs: GenTraversable[_]): ResultOfTheSameElementsInOrderAsApplication

    Permalink
    Definition Classes
    Matchers
  168. val theSameInstanceAs: TheSameInstanceAsPhrase

    Permalink
    Definition Classes
    Matchers
  169. val they: TheyWord

    Permalink
    Attributes
    protected
    Definition Classes
    FlatSpecLike
  170. def thrownBy(fun: ⇒ Any): ResultOfThrownByApplication

    Permalink
    Definition Classes
    Matchers
  171. def toString(): String

    Permalink
    Definition Classes
    FlatSpec → AnyRef → Any
  172. val typeCheck: TypeCheckWord

    Permalink
    Definition Classes
    MatcherWords
  173. def typeCheckedConstraint[A, B](implicit equivalenceOfA: Equivalence[A], ev: <:<[B, A]): CanEqual[A, B]

    Permalink
    Definition Classes
    TripleEquals → TripleEqualsSupport
  174. implicit def unconstrainedEquality[A, B](implicit equalityOfA: Equality[A]): CanEqual[A, B]

    Permalink
    Definition Classes
    TripleEquals → TripleEqualsSupport
  175. val value: ValueWord

    Permalink
    Definition Classes
    Matchers
  176. final def wait(): Unit

    Permalink
    Definition Classes
    AnyRef
    Annotations
    @throws( ... )
  177. final def wait(arg0: Long, arg1: Int): Unit

    Permalink
    Definition Classes
    AnyRef
    Annotations
    @throws( ... )
  178. final def wait(arg0: Long): Unit

    Permalink
    Definition Classes
    AnyRef
    Annotations
    @throws( ... )
  179. def withClue[T](clue: Any)(fun: ⇒ T): T

    Permalink
    Definition Classes
    Assertions
  180. def withFixture(test: NoArgTest): Outcome

    Permalink
    Attributes
    protected
    Definition Classes
    TestSuite
  181. val writable: WritableWord

    Permalink
    Definition Classes
    MatcherWords

Deprecated Value Members

  1. final def execute: Unit

    Permalink
    Definition Classes
    Suite
    Annotations
    @deprecated
    Deprecated

    The parameterless execute method has been deprecated and will be removed in a future version of ScalaTest. Please invoke execute with empty parens instead: execute().

  2. def trap[T](f: ⇒ T): Throwable

    Permalink
    Definition Classes
    Assertions
    Annotations
    @deprecated
    Deprecated

    The trap method is no longer needed for demos in the REPL, which now abreviates stack traces, and will be removed in a future version of ScalaTest

Inherited from ScalaTutorialSection

Inherited from Section

Inherited from Matchers

Inherited from Explicitly

Inherited from MatcherWords

Inherited from Tolerance

Inherited from FlatSpec

Inherited from FlatSpecLike

Inherited from Documenting

Inherited from Alerting

Inherited from Notifying

Inherited from Informing

Inherited from CanVerb

Inherited from MustVerb

Inherited from ShouldVerb

Inherited from TestRegistration

Inherited from TestSuite

Inherited from Suite

Inherited from Serializable

Inherited from Serializable

Inherited from Assertions

Inherited from TripleEquals

Inherited from TripleEqualsSupport

Inherited from AnyRef

Inherited from Any

Ungrouped