0

I don't understand why sometimes class are created inside an object in Scala, just like the following code shows.

object polynomials { 
  class Poly(terms0: Map[Int, Double]) {
    val terms = terms0 withDefaultValue 0.0

    def +(other: Poly) = new Poly(terms ++ (other.terms map adjust))

    def adjust(term: (Int, Double)): (Int, Double) = {
        val (exp, coeff) = term
        exp -> (coeff + terms(exp))
    }
    override def toString = 
     (for ((exp, coeff) <- terms.tolist.sorted.reverse) yield coeff 
     + ”x^” + exp) mkString “+” 
  }

  val p1 = new Poly(Map(1 -> 2.0, 3 -> 4.0, 5 -> 6,2))
  val p2 = new Poly(Map(0 -> 3.0, 3 -> 7.0)

  p1 + p2
}
jwvh
  • 50,871
  • 7
  • 38
  • 64
Hillary
  • 135
  • 1
  • 8

2 Answers2

4

There are a number of reasons for doing this that relate to naming and data hiding.

  1. The nested class is inside the scope of the object rather than in the wider package scope, so it can have a simpler name without clashing with other package classes. It makes an explicit link between the class and the object.
  2. The class can be private to the object so it is not visible outside the scope of the object. This is often used for a class that implements an abstract interface where only the interface is visible outside the object
  3. The nested class can access members of the object directly, including private members that are not externally visible.
Tim
  • 26,753
  • 2
  • 16
  • 29
-1

Defining an object in Scala is like defining a class in Java that has only static methods. However, in Scala an object can extend another superclass, implement interfaces, and be passed around as though it were an instance of a class. (So it's like the static methods on a class but better).

An object has exactly one instance (you can not call new MyObject). You can have multiple instances of a class.

Object serves the same (and some additional) purposes as the static methods and fields in Java.

So if you have for example a Circle object and a Circle class then Circle object would have generic properties like PI and methods like CalculateArea() whereas Circle class would have instance specific properties like Colour, Radius etc.

msteel9999
  • 305
  • 2
  • 15