hegash
hegash

Reputation: 863

Scala class that creates an instance of another class

I have a matrix class defined as follows:

class Matrix(private val A: Array[Array[Double]]){...}

I would like to create a vector class, and since vectors are matrices, it would make sense for a vector object to just be a matrix object. However, I would like to construct vector objects by passing an Array[Double] as a parameter, and not an Array[Array[Double]].

Essentially, I would like a wrapper for my matrix class that takes an Array[Double] as a parameter - e.g. Array(1,2) - and creates the appropriate matrix - so in this case Matrix(Array(Array(1),Array(2))

Something like:

class Vec(array: Array[Double]){
    private val size = array.size
    private val arrayAsMatrix: Array[Array[Double]] = Array.ofDim[Double](size, 1)
    for(i <- 0 until n) matrix(i) = Array(array(i))
    //create a Matrix(arrayAsMatrix)
}

I would then like to use all of the matrix functions I have defined in Matrix (addition, multiplication, etc.) as normal - and perhaps add some new methods to Vec such as a norm.

I'm quite new to Scala so haven't really made any progress with this so far at all.

Upvotes: 0

Views: 345

Answers (1)

bobah
bobah

Reputation: 18864

In Scala I would first try to write an extension class (I think they are called "type class") to treat arrays like vectors and matrices instead of trying to force the API into object oriented space. They are zero-cost abstraction (compiler understands it well).

object LinearAlgebra {
  implicit class VectorOps(val self: Array[Double]) extends AnyVal {
    def rank = ???
    ???
  }

  implicit class MatrixOps(val self: Array[Array[T]]) extends AnyVal {
    def rank = ???
    ???
  }
}

Then you can write code like:

import LinearAlgebra._
val vector = Array(1,2,3,4)
// this will effectively be "new VectorOps(vector).rank"
// but the compiler will optimize the temp object allocation out
println(vector.rank)

If done this way, many incorrect things will become compile time syntax error. Which would not be the case with object oriented design.

Upvotes: 2

Related Questions