首页 > 其他 > 详细

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

时间:2015-08-08 01:08:33      阅读:325      评论:0      收藏:0      [点我收藏+]

原文链接 http://stackoverflow.com/questions/16348541/scala-example-use-for-early-definition-early-initializer-pre-initialized-fi#

 


 

 

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
  )
}

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

原文:http://www.cnblogs.com/ihongyan/p/4712298.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!