score:4

Accepted answer

If the reason for creating the copy of the injected constructor objects is primarily to be able to expose them externally, then you can instead write:

class Trade (
              val direction : Char,
              val instrument : Instrument,
              val price : BigDecimal,
              val quantity : BigDecimal,
              val counterparty : Party)
{
  // some great methods below...

}

or even better, use case classes: http://www.scala-lang.org/old/node/107

case class Trade (
              direction : Char,
              instrument : Instrument,
              price : BigDecimal,
              quantity : BigDecimal,
              counterparty : Party) {
  // some great methods below...

}

score:0

A side note on Rational implementation,

case class Rational (n : Int, d : Int) {
  def +(that: Rational) = Rational (n*that.d + that.n*d, d*that.d)
}

Here the + operator is overloaded to operate on Rational. Then

val a = Rational(1,2)
val b = Rational(3,4)
val c = a+b

and so

c: Rational = Rational(10,8)

score:1

You don't have to create duplicates. You can do:

class Rational (val n : Int, val d : Int)

This gives You class with immutable fields n and d Or You can use case class

 case class Rational (n : Int, d : Int)

score:3

You could just define your class Trade like this:

class Trade(val direction: Char, val instrument: Instrument, ...) // etc

In other words, put val in front of the constructor parameters. No need for all the duplication.


Related Query

More Query from same tag