Scala: Example use for early definition / early initializer / pre-initialized fields

Scala allows you to make early definitions like so:

trait A {
  val v: Int
}

class B extends { val v = 4 } with A

What is an example use of this feature?

Answers


Whenever the value is used for the trait initialization. So for eaxmple for this trait:

trait UsefulTrait {
  val parameter : Int
  private val myHelperObject = new MyExpensiveClass(parameter)
}

The parameter is used to substitute for a constructor parameter. However the parameter should be rather made an abstract method, because it leaves more free space to the implementer.


Let's see a example from the Programming in Scala book (page 451). If we have a definition like this:

trait RationalTrait {
   val numerArg: Int
   val denomArg: Int
}

Then numerArg and denomArg are called abstract vals & the trait can be used directly without extends, like this:

val x = new RationalTrait {
   val numerArg = 1
   val denomArg = 2
}

Or

val y = new {
   val numerArg = 1
   val denomArg = 1
} with RationalTrait

The above two are both valid Pre-initializing of abstract val in trait, except that when you need to put an expression value to abstract vals, you can only use the later form, like this:

val z = new {
  val numerArg = 1 * x
  val denomArg = 2 * x
} with RationalTrait

Another interesting example in book is to Pre-initialized fields in a class definition.

class RationalClass(n: Int, d: Int) extends {
  val numerArg = n
  val denomArg = d
} with RationalTrait {
  def + (that: RationalClass) = new RationalClass(
    numer * that.denom + that.numer * denom,
    denom * that.denom
  )
}

Need Your Help

exception while running pre-existing Audit report in JasperReports Server

java jasper-reports weblogic jasperserver

I am getting below exception while running any of the pre-existing Audit report in JasperReports Server.

OOzie: Unable to find hive-default.xml

hive cloudera oozie

I am new to oozie and want to add a hive job to my workflow. Could you please tell me where could I find or how could I create the hive-default.xml. I have actually installed everthing via cloudera

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.