zoukankan      html  css  js  c++  java
  • 【转】Scala: Example use for early definition / early initializer / pre-initialized fields

    原文链接 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
      )
    }
  • 相关阅读:
    java面试的那些事
    java多线程实现复制大文件
    java心跳发送
    Java实现缓存(LRU,FIFO)
    java并发阻塞队列
    java之路
    Intellij IDEA中使用Protobuf的正确姿势
    Flink JobManager HA模式部署(基于Standalone)
    查看Flink的Job Graph时的问题
    Flink从Kafka 0.8中读取多个Topic时的问题
  • 原文地址:https://www.cnblogs.com/ihongyan/p/4712298.html
Copyright © 2011-2022 走看看