Apr 4, 2013

OOP Tutorial: 2-dimensional Vector as Scala Object

As before in Java: When starting to learn object orientated programming, a good first example is the following: Modelling a 2-dimensional vector over the real numbers could result in this (pay attention to the overloading of * and +. Compare to the verbose Java variant):

package de.bigdev

class Vector(val x: Double, val y: Double) {
    
  /**
   * Addition of two vectors
   *
   * @param v
   * @return the sum with v
   */
  def +(v: Vector) = new Vector(x + v.x, y + v.y)
  
  /**
   * Scalar Mulitplication with a constant
   *
   * @param c
   * @return the scalar multiplication with c
   */
  def *(c: Double) = new Vector(c * x, c * y)

  /**
   * Length of two vectors
   *
   * @return length
   */
  def length = math.sqrt(x * x + y * y)

  /**
   * Scalar Product of two vectors
   *
   * @param v
   * @return the scalar product with v
   */
  def *(v: Vector) = x * v.x + y * v.y
  
  /**
   * Angle between two vectors
   *
   * @param v
   * @return the angle with v in degrees
   */
  def angle(v: Vector) = math.acos(this * v / (this.length * v.length)) *
    180.0 / Math.PI

  override def toString = "[" + x + "," + y + "]"
}

For execution we need a main method (pay attention to the usage of *, + and angle):

package de.bigdev

object VectorTest {

  /**
   * for testing only... or use ScalaTest!
   */
  def main(args: Array[String]) {

    val v = new Vector(1, 1)
    val w = new Vector(-1, -1)

    println("Vector algebra")
    println("==============")
    println("addition      : " + v + " + " + w + " = " + (v + w))
    println("scalar multip.: 2 * " + v + " = " + v * 2)
    println("length        : ||" +v + "|| = " + v.length)
    println("scalar product: " + v + " * " + w + " = " + v * w)
    println("angle         : angle(" + v + ", " + w
      + ") = " + math.round(v angle w) + "°")
  }
}

The output on the console is:

Vector algebra
==============
addition      : [1.0,1.0] + [-1.0,-1.0] = [0.0,0.0]
scalar multip.: 2 * [1.0,1.0] = [2.0,2.0]
length        : ||[1.0,1.0]|| = 1.4142135623730951
scalar product: [1.0,1.0] * [-1.0,-1.0] = -2.0
angle         : angle([1.0,1.0], [-1.0,-1.0]) = 180°

No comments:

Post a Comment