scala - Naming fields in immutable functional objects -


i learning scala @ moment via odersky's programming scala 2nd book , have covered chapter 6 discusses functional objects. in chapter, main example centres around creating class represent rational numbers , arithmetic of rational numbers.

his cut-down class looks like:

class rational (n : int, d : int) {    val numer : int = n   val denom : int = d    def add (that: rational) : rational =      new rational (       numer * that.denom + that.numer * denom, denom * that.denom) } 

in order achieve immutability, has introduced 2 new variables, numer , denom, represent same concepts class parameters, n , d. based on knowledge far, means if want create immutable functional objects in scala, have go through process of creating duplicates of class parameters can tedious. example, if wanted create class represent trade, have this:

class trade (               direction : char,               instrument : instrument,               price : bigdecimal,               quantity : bigdecimal,               counterparty : party              ) {    val direction_ = direction   val instrument_ = instrument   val price_ = price   val quantity_ = quantity   val counterparty_ = counterparty    // great methods below...  } 

the way around have thought put underscores after variable names above because can't think of name direction, instrument, price etc. know best practice here other scala programmers have found avoid getting variable-naming-paralysis mode.

if reason creating copy of injected constructor objects able expose them externally, can instead write:

class trade (               val direction : char,               val instrument : instrument,               val price : bigdecimal,               val quantity : bigdecimal,               val counterparty : party) {   // great methods below...  } 

or 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) {   // great methods below...  } 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -